throw keyword in java
The 'throw'
keyword is used to throw an exception explicitly.
When a throw statement is encountered and executed, execution of the further code is stopped and returned to the caller.
The throw
statement takes a java.lang.Throwable as an argument.
The Throwable is propagated up the call stack until it is caught by an appropriate catch block.
Any method that throws an exception that is not a RuntimeException must also declare the exceptions it throws using a 'throws'
modifier on the method declaration
Example:
- public class ReadFileExample
- {
- public method readFile(String filename) throws IOException
- {
- <statements>
- if (error)
- {
- throw new IOException("error reading file");
- }
- System.out.println("file read done");
- }
- }
public class ReadFileExample { public method readFile(String filename) throws IOException { <statements> if (error) { throw new IOException("error reading file"); } System.out.println("file read done"); } }
In the above example, We are throwing IOException explicitly based on some condition inside readFile() method and hence further execution will be stopped.
So throw
keyword must be used if we want to throw an exception explicitly.
When using the throw
keyword to throw a checked exception from within a method, the method should do one of the following options
1) Declares the throws clause followed by the exceptions thrown by the throw statements
2) Should Catch the exceptions thrown by the throw statement.
When using the throw
keyword to throw a Runtime exception from within a method, Then throws is optional
If we write catch block to handle the exception then same method will handle that exception otherwise caller can handle the exception