Numerator
Numerator

Reputation: 1409

Try, Catch and Finally blocks

public class D {

void myMethod() {
    try {
        throw new IllegalArgumentException();
    } catch (NullPointerException npex) {
        System.out.println("NullPointerException thrown ");
    } catch (Exception ex) {
        System.out.println("Exception thrown ");
    } finally {
        System.out.println("Done with exceptions ");
    }
    System.out.println("myMethod is done");
}

public static void main(String args[]) {
    D d = new D();
    d.myMethod();
}

}

I don't understand how come "myMethod is done" also being printed. Exception was throwed, so it suppose to find a matching catch and do the finally block, but it continues on the myMethod method and prints the myMethod is done, which is not part of the finally block. Why?

Upvotes: 3

Views: 357

Answers (6)

WaelJ
WaelJ

Reputation: 3012

On the other hand if you have the following:

void myMethod() {
    try {
        throw new IllegalArgumentException();

        System.out.println("Line after exception");   /// new line added here

    } catch (NullPointerException npex) {
        System.out.println("NullPointerException thrown ");
    } catch (Exception ex) {
        System.out.println("Exception thrown ");
    } finally {
        System.out.println("Done with exceptions ");
    }
    System.out.println("myMethod is done");
}

public static void main(String args[]) {
    D d = new D();
    d.myMethod();
}

Then "Line after exception" would NOT print.

Upvotes: 5

ed.
ed.

Reputation: 1393

Presumably it says "Exception thrown ", then "Done with exceptions ", and then "myMethod is done". That's what it should do.

Because you're catching the exception yourself it will just continue execution after the whole try-catch-finally block is finished. That's the point of a catch statement.

Upvotes: 1

fireshadow52
fireshadow52

Reputation: 6516

Techincally speaking, you already dealt with the exception(s), and therefore execution continues.

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

You've caught the exception, which means it won't propagate any further. Execution continues immediately after the try statement, which is the statement that prints myMethod is done.

Upvotes: 1

MByD
MByD

Reputation: 137322

You handled the exception, so the method processing continues.

Upvotes: 2

Blorgbeard
Blorgbeard

Reputation: 103467

This is how try-catch-finally is intended to work. Because you caught the exception, it's considered to have been dealt with, and execution continues as normal.

If you hadn't caught it, or had re-thrown it, then "myMethod is done" would not have been printed, and the exception would have bubbled up the stack until it was caught somewhere else.

Note that the finally block always executes, exceptions or no.

Upvotes: 9

Related Questions