Tuesday, 19 May 2015

throws keyword in Java exception handling

In a called method if you want to leave it to the calling method to handle any exception that is thrown by the called method it can be done using throws keyword.

A method can just declare the exception it may throw using the throws keyword and callers of the method have to provide exception handling for those exceptions (or they can also declare them using throws).

General form of a method declaration that includes a throws clause

type method-name(parameter-list) throws exception-list
// body of method

Here, exception-list is a comma-separated list of the exceptions that a method can throw.

Throws is necessary for all checked exceptions only. If a method may throw checked exceptions and does not provide any exception handling for it, then those exception must be declared in the throws clause. If they are not, it will result in a compile-time error.

For unchecked exception anyway compiler doesn't force any try-catch block so throws is also optional, not declaring unchecked exception in a throws clause won't result in any compiler error.

Example if Throws is not used with Checked exception

throws keyword

It can be seen that it results in compiler error as the method has no try catch block to handle exception and it is not even declaring the thrown exceptions using throws clause.

Example with throws

To fix it with throws we need to declare the exceptions, displayFile() method, can throw using throws clause. Then in main method we need to enclose the method call in try-catch block to handle the error.

public class ThrowsDemo {
    public static void main(String[] args) {
        }catch(IOException ioExp){
    static void displayFile() throws IOException{
        System.out.println("In displayFile method");  
        throw new IOException();


That's all for this topic throws keyword in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. throw statement
  2. Difference between throw and throws
  3. Multiple catch blocks
  4. Nested try statements
  5. final Vs finally Vs finalize
  6. Java Exception Handling interview questions

You may also like -

No comments:

Post a Comment