1

I have the following code. In that fn2 is actually throwing an exception and it is caught in the function itself. In the function fn1 the compiler is complaining about unhandled exception since fn2 is declared to be throwing an Exception.

Why it is so? Since the exception is caught inside fn2 it shouldn't be complaining right?

Please explain the behavior.

public class ExepTest {

/**
 * @param args
 */
public static void main(String[] args) {

    ExepTest exT = new ExepTest();
    exT.fn1();

}
public void fn1(){
    fn2();//compilation error
}
public void fn2() throws Exception{

    try{
        throw new Exception();
    }
    catch(Exception ex){
        System.out.println("Exception caught");
    }
}
}

7 Answers 7

10

Compiler doesn't/can't know that at runtime no exception will be throwed by fn2() since it's declared that it may throw an Exception, that's why you got an error.

Sign up to request clarification or add additional context in comments.

2 Comments

In other words: If you tell it that a methods throws Exception then the compiler will believe you. It won't check if that's actually the case (in some cases he can't even check).
@Joachim: It's a relationship based on mutual trust.
3

Remove the throws Exception from fn2() signature

Comments

1

The signature of the method fn2 is all that matters here. In that signature you declare that fn2 may throw an Exception. Any code that calls a method that may throw an Exception must handle the eexception.

Comments

1

public void fn2() throws Exception. The compiler see that declaration and expect each caller to fn2 to handle / rethrow the exception.

Comments

1

Exception is thrown BY fn2, not inside it. So it will be actually thrown where it is called. Since it is called in fn1, it is behaving like this.

Comments

1

You need to surround the call to fn2() in a try-catch block, or declare that fn1 also throws an exception.

Comments

1
public void fn1(){
    fn2();//compilation error
}
public void fn2() throws Exception{

    try{
        throw new Exception();
    }
    catch(Exception ex){
        System.out.println("Exception caught");
    }
}
}

Here compiler will not recognize that you have handled exception or not. It just assumes that fn2 throws exception as you have declared to be and that's why it's showing error.

To run program either remove throws Exception from fn2 or write throws Exception in fn1 or handle it in try..catch in fn1.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.