Bharat Bhardwaj Bharat Bhardwaj - 1 year ago 32
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 {
} catch (Throwable th) {
try {
new Exception();
} catch (Exception e) {
} finally {

Unable to figure out the flow of execution!!

Answer Source

The output of above mentioned code will be


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){
        catch(Throwable th)
            try{ throw new Exception(); }
            catch(Exception e){System.out.print("Exception");}