Ammu
Ammu

Reputation: 5137

Java exception handling

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");
    }
}
}

Upvotes: 1

Views: 245

Answers (7)

Harry Joy
Harry Joy

Reputation: 59694

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.

Upvotes: 1

Ido Weinstein
Ido Weinstein

Reputation: 1168

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

Upvotes: 1

Muhammad Yasir
Muhammad Yasir

Reputation: 646

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.

Upvotes: 1

insumity
insumity

Reputation: 5479

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.

Upvotes: 10

MByD
MByD

Reputation: 137432

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

Upvotes: 1

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

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.

Upvotes: 1

Bozho
Bozho

Reputation: 597382

Remove the throws Exception from fn2() signature

Upvotes: 3

Related Questions