The throws keyword tells the program that a method might cause an error that needs handling.
Throws keyword in Java
Start learning this pattern below
Jump into concepts and practice - no test required
returnType methodName(parameters) throws ExceptionType1, ExceptionType2 { // method body }
throws keyword.public void readFile() throws IOException { // code that might throw IOException }
public int divide(int a, int b) throws ArithmeticException { return a / b; }
throws.public void process() throws IOException, SQLException { // code that might throw IOException or SQLException }
This program defines a method readFile that declares it throws IOException. The main method calls it inside a try-catch block to handle possible errors.
import java.io.*; public class ThrowsExample { public static void readFile(String filename) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(filename)); System.out.println("First line: " + reader.readLine()); reader.close(); } public static void main(String[] args) { try { readFile("test.txt"); } catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); } } }
The throws keyword only declares exceptions; it does not handle them.
Checked exceptions must be declared or caught; unchecked exceptions (like NullPointerException) do not need to be declared.
Use throws to pass responsibility for handling exceptions to the method caller.
The throws keyword tells others your method might cause an error.
It helps keep code clean by letting callers handle errors.
Always declare checked exceptions your method can throw.
Practice
What is the main purpose of the throws keyword in Java?
Solution
Step 1: Understand the role of
Thethrowsthrowskeyword is used in a method signature to declare that the method might throw certain checked exceptions.Step 2: Differentiate from other keywords
It does not catch exceptions (that'stry-catch), nor create exceptions or stop the program immediately.Final Answer:
To declare that a method might throw certain checked exceptions -> Option AQuick Check:
throwsdeclares exceptions [OK]
- Confusing throws with catch
- Thinking throws creates exceptions
- Believing throws stops program immediately
Which of the following is the correct way to declare a method that might throw an IOException?
public void readFile() _____ IOException { }Solution
Step 1: Recall correct syntax for exception declaration
In Java, the keyword to declare exceptions a method might throw isthrows.Step 2: Check options for syntax correctness
throwis used to actually throw an exception inside method body, not in declaration.thrownandthrows neware invalid.Final Answer:
throws -> Option CQuick Check:
Method declaration usesthrows[OK]
- Using 'throw' instead of 'throws' in method signature
- Adding 'new' after throws
- Using non-existent keywords like 'thrown'
What will be the output of the following code?
import java.io.*;
public class Test {
public static void risky() throws IOException {
throw new IOException("Error happened");
}
public static void main(String[] args) {
try {
risky();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}Solution
Step 1: Analyze method throwing exception
The methodrisky()declares it throwsIOExceptionand actually throws it with message "Error happened".Step 2: Check exception handling in main
Themainmethod callsrisky()inside a try block and catchesIOException, printing the exception message.Final Answer:
Error happened -> Option AQuick Check:
Exception caught and message printed [OK]
- Thinking throws causes compile error if caught
- Expecting no output because exception thrown
- Confusing throws with throw inside method body
Identify the error in the following code snippet:
public void process() {
riskyMethod() throws IOException;
}Solution
Step 1: Check syntax of throws usage
Thethrowskeyword cannot be used inside a method body; it belongs in the method signature.Step 2: Analyze exception handling requirements
CallingriskyMethod()which throwsIOExceptionrequires either a try-catch block or declaringthrows IOExceptioninprocess().Step 3: Combine all errors
All these issues are present: wrong throws usage, missing try-catch, and missing throws declaration.Final Answer:
All of the above -> Option DQuick Check:
Throws only in signature + handle exceptions [OK]
- Using throws inside method body
- Not handling checked exceptions properly
- Forgetting to declare throws in method signature
You have a method readData() that calls two other methods: openFile() and parseFile(). Both can throw IOException. How should you declare readData() to properly handle exceptions?
Solution
Step 1: Understand exception propagation
IfopenFile()andparseFile()throwIOException,readData()must either handle or declare these exceptions.Step 2: Choose proper declaration
Declaringthrows IOExceptioninreadData()lets the caller decide how to handle exceptions, keeping code clean and clear.Step 3: Evaluate other options
Ignoring exceptions is bad practice. Declaringthrows Exceptionis too broad. Exceptions are not handled automatically.Final Answer:
Declare readData() with throws IOException and let caller handle it -> Option BQuick Check:
Declare checked exceptions to propagate [OK]
- Ignoring exceptions instead of declaring or catching
- Declaring too broad exceptions like Exception
- Assuming exceptions are handled automatically
