Shahabuddin Ansari
Shahabuddin Ansari

Reputation: 11

Getting compilation error in main even though try catch finally block is added in the calling method

I am trying to run the below code but getting compilaton error as "Unhandled exception type FileNotFoundException", as per my understanding this should not happen since try catch and finally blocks are added in the calling method.

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Test
{
    public static void main(String[] args)
    {
        myMethod();
    }

    public static void myMethod() throws FileNotFoundException
    {
        try
        {
            System.out.println("In the try block");
            FileInputStream fis = new FileInputStream("file.txt");
        }
        catch(Exception e)
        {
            System.out.println("in the catch block");
            throw e;
        }
        finally
        {
            System.out.println("in the finally block");
        }
    }
}

Upvotes: 0

Views: 156

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

Remove throws FileNotFoundException from the myMethod signature (and then you'll need to remove throw e; from the catch block).

Or, add a try and catch to your main method (to handle the FileNotFoundException that you have indicated myMethod can throw).

Or, add throws FileNotFoundException to the signature of main (as pointed out by Andreas in the comments).

In short, the compiler will not allow you to have a code path with checked exceptions that are not handled.

Upvotes: 3

Chathura Buddhika
Chathura Buddhika

Reputation: 2195

In the catch block, you are throwing the Exception again once you catch it. If you really want to throw it from the myMethod() even after catch it, just add another try-catch to the main method.

public static void main(String[] args){
    try{
        myMethod();
    }catch(FileNotFoundException e){
        System.out.println("catch block in main");
    }
}

Or else if you want to just catch the Exception in your myMethod(), don't throw it back.

try{
    System.out.println("In the try block");
    FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e){
    System.out.println("in the catch block");
}
finally{
    System.out.println("in the finally block");
}

you can read more about re-throwing exceptions in following question.

Rethrow exception in java

Upvotes: 0

Related Questions