throws keyword in java
The "throws"
keyword can be applied to a method to indicate that, the method raises particular types of exceptions and it is not handling that exception.
So this signals the caller that, It has to handle the exception thrown by the method.
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 We are specifying the same to the caller using 'throws'
keyword at the method signature.
When we throw a checked exception from 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 we throw a Runtime exception from 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.
If we don’t use throws
keyword and if we are throwing checked exception in a method without handling it then we will get compile time error.
Example:
- public class ReadFileExample
- {
- public method readFile(String filename)
- {
- <statements>
- if (error)
- {
- throw new IOException("error reading file");
- }
- System.out.println("file read done");
- }
- }
public class ReadFileExample { public method readFile(String filename) { <statements> if (error) { throw new IOException("error reading file"); } System.out.println("file read done"); } }
In the above code, we are throwing IOException but we are neither handling it using try-catch nor specifying “throws
” at the method signature.
If we throw runtime exception , then throws
is optional no matter whether we handle the exception or not.
Example:
- public void divide(int num1, int num2){
- double res=0.0;
- if(num2 == 0 ) {
- throw new ArithmeticException("denominator == 0");
- }
- else{
- res=num1/num2;
- }
- System.out.println("result is "+res);
- }
public void divide(int num1, int num2){ double res=0.0; if(num2 == 0 ) { throw new ArithmeticException("denominator == 0"); } else{ res=num1/num2; } System.out.println("result is "+res); }
In the above example, we are throwing Run time exception if second number is ‘0‘ but we are neither handling it nor using throws
at the method signature as its optional in case of Run time exception.