Throws Keyword
Throws Keyword
A school program needs reliable data and clear rules. A throws clause declares checked exceptions a method may propagate. The caller must handle or declare those failures; the declaration itself does not raise an exception.
Understand
A throws clause declares checked exceptions a method may propagate.
Apply
Trace the Java example, predict its output and explain the result before running it.
Avoid mistakes
Declaring throws does not implement recovery and does not mean the method always fails.
throws Keyword in Java
The throws keyword in Java is used to declare exceptions. It tells the compiler that a method might throw one or more exceptions. This keyword doesn’t handle the exception directly; rather, it shifts the responsibility to the method caller.
Think of it as a way to say: “Hey, this method might cause a problem — be prepared to handle it!”
Why Use throws in Java?
In Java, when a method has a chance of throwing a checked exception (like IOException or SQLException), it must either:
- Handle it using a
try-catchblock - Declare it using the
throwskeyword
Failing to do either results in a compilation error.
Basic Syntax
return_type method_name(parameters) throws ExceptionType1, ExceptionType2 {
// method body
}
Example 1: Declaring a Method That Throws an Exception
import java.io.IOException;
public class FileProcessor {
public static void readFile() throws IOException {
throw new IOException("File not found!");
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Caught Exception: File not found!
Explanation
Java · example discussed here
import java.io.IOException;
public class FileProcessor {
public static void readFile() throws IOException {
throw new IOException("File not found!");
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
The readFile() method declares that it might throw an IOException. In the main() method, we handle it using a try-catch block. Without the throws declaration, the compiler would complain.
Example 2: Multiple Exceptions
import java.io.IOException;
import java.sql.SQLException;
public class MultiExceptionDemo {
public static void riskyMethod() throws IOException, SQLException {
if (System.currentTimeMillis() % 2 == 0) {
throw new IOException("IO problem");
} else {
throw new SQLException("DB problem");
}
}
public static void main(String[] args) {
try {
riskyMethod();
} catch (IOException | SQLException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Caught Exception: IO problem
// or
Caught Exception: DB problem
Explanation
Java · example discussed here
import java.io.IOException;
import java.sql.SQLException;
public class MultiExceptionDemo {
public static void riskyMethod() throws IOException, SQLException {
if (System.currentTimeMillis() % 2 == 0) {
throw new IOException("IO problem");
} else {
throw new SQLException("DB problem");
}
}
public static void main(String[] args) {
try {
riskyMethod();
} catch (IOException | SQLException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
This example shows how a method can declare multiple exceptions using throws. Depending on the condition, either IOException or SQLException is thrown. The catch block handles both types using multi-catch (| syntax).
Example 3: Propagating Exceptions to Caller
import java.io.*;
public class PropagateDemo {
public static void method1() throws IOException {
throw new IOException("Thrown from method1");
}
public static void method2() throws IOException {
method1(); // propagating the exception
}
public static void main(String[] args) {
try {
method2();
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Caught Exception: Thrown from method1
Explanation
Java · example discussed here
import java.io.*;
public class PropagateDemo {
public static void method1() throws IOException {
throw new IOException("Thrown from method1");
}
public static void method2() throws IOException {
method1(); // propagating the exception
}
public static void main(String[] args) {
try {
method2();
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Here, method1() throws an exception. Instead of handling it inside method2(), we use throws to let it bubble up. Finally, main() handles it. This is known as exception propagation.
Checked vs Unchecked with throws
- Checked exceptions (like
IOException) must be either handled or declared withthrows. - Unchecked exceptions (like
NullPointerException) don’t require declaration.
Real-world Analogy
Imagine a pizza delivery driver gets stuck in traffic. Instead of calling every customer to say, “I’ll be late,” they notify the manager (the calling method), who then handles the customer interactions. This is what throws does — it delegates responsibility upward.
Best Practices
- Don’t overuse
throws Exception— be specific about what can go wrong. - Only use
throwswhen the method really can’t or shouldn’t handle the exception. - Document thrown exceptions using JavaDoc (
@throws).
Conclusion
The throws keyword is your tool for delegation in Java’s exception ecosystem. It empowers methods to signal problems without dictating how they should be handled. In production-grade systems, clean exception propagation using throws ensures modular and testable code.
Up next, you’ll learn about throw — the partner of throws — to actually generate exceptions when needed.
Important boundaries and mistakes
Declaring throws does not implement recovery and does not mean the method always fails.
Try the school example
Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Declaring throws does not implement recovery and does not mean the method always fails..
Java 17 · Main.java · complete practice program
public class Main {
static void readMark() throws java.io.IOException {
throw new java.io.IOException("example");
}
public static void main(String[] args) {
try {
readMark();
}
catch (java.io.IOException e) {
System.out.println("Read failed");
}
}
}
Worked answer and reasoning
Java 17 · Main.java · source repeated for this answer
public class Main {
static void readMark() throws java.io.IOException {
throw new java.io.IOException("example");
}
public static void main(String[] args) {
try {
readMark();
}
catch (java.io.IOException e) {
System.out.println("Read failed");
}
}
}
Expected output
Read failedA throws clause declares checked exceptions a method may propagate. The caller must handle or declare those failures; the declaration itself does not raise an exception.
Declaring throws does not implement recovery and does not mean the method always fails.
Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.
Check your understanding
What to remember
A throws clause declares checked exceptions a method may propagate. The caller must handle or declare those failures; the declaration itself does not raise an exception. Declaring throws does not implement recovery and does not mean the method always fails.
Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide and Java 17 language specification.
Reaching the recap and completing the quizzes are separate milestones.