Exception handling – throws
We already know that, we can handle exceptions using try-catch block.
But in some cases, its good to use “throws” instead of using ty-catch block.
In some cases, its not required to handle the exception in a method which is called by another method so that caller will handle this exception.
Client program knows how to respond to client when exception occurs
If client program is calling any method of other class to perform some logic and if any exception comes in that method then its better to leave it for client to handle it.
“throws” should be used in such scenarios where we need to give responsibility of exception handling to caller
But, signal the caller that you need to handle the exception using “throws”.
“throws” should be used after the method signature
Note :
"throws" force the caller to handle the exception if its checked exception only, If not handled then compiler throws an error. If its unchecked exception then its optional for caller to handle it, compiler won’t force to handle.
Syntax :
- public void myMethod() throws ArithmeticException, NullPointerException
- {
- // Statements that might throw an exception
- }
public void myMethod() throws ArithmeticException, NullPointerException { // Statements that might throw an exception }
Example:
Below class is responsible to read content from file if filename is valid.
- package com.kb.state;
- import java.io.IOException;
- public class FileReadOperation {
- public void readFile(String fileName) throws IOException{
- if(fileName==null){
- throw new IOException("File name is required");
- }
- else{
- System.out.println("Performed file read operation");
- }
- }
- }
package com.kb.state; import java.io.IOException; public class FileReadOperation { public void readFile(String fileName) throws IOException{ if(fileName==null){ throw new IOException("File name is required"); } else{ System.out.println("Performed file read operation"); } } }
If filename is null then throw an exception
Once exception is thrown, we need to handle it, hence handled it using “throws”
This will force the caller to handle it
- package com.kb.state;
- public class ExceptionThrowsExample {
- public static void main(String args[])
- {
- try {
- FileReadOperation fileReadOperation = new FileReadOperation();
- fileReadOperation.readFile(null);
- } catch (Exception e) {
- System.out.println(e);
- }
- System.out.println("End of Program");
- }
- }
package com.kb.state; public class ExceptionThrowsExample { public static void main(String args[]) { try { FileReadOperation fileReadOperation = new FileReadOperation(); fileReadOperation.readFile(null); } catch (Exception e) { System.out.println(e); } System.out.println("End of Program"); } }