Bharat Bhardwaj Bharat Bhardwaj - 4 months ago 5
Java Question

Is it like reThrowing the same exception?

When i executed this code i got "finally"

public class Tester {
static void method() throws Exception {
throw new Exception();
}

public static void main(String... args) {
try {
method();
} catch (Throwable th) {
try {
new Exception();
} catch (Exception e) {
System.out.print("Exception");
} finally {
System.out.print("finally");
}
}
}
}


Unable to figure out the flow of execution!!

Answer

The output of above mentioned code will be

finally

If you're wondering why the output isn't

Exception finally

then it is because in the following line of code

try {
        new Exception();
    }

you're only declaring a new Exception object, you're not really throwing it.

if you want the output to be Exception finally then you have to throw that object by putting throw new Exception(); instead of new Exception();

The code would then look like:

public class HelloWorld{
    static void method() throws Exception{ throw new Exception(); }

    public static void main(String... args){
        try{method();}
        catch(Throwable th)
        {
            try{ throw new Exception(); }
            catch(Exception e){System.out.print("Exception");}
            finally{System.out.print("finally");}    
        }
    }
} 

Output

Exceptionfinally