I wanted to provide an example of the try/catch block introduced in part 1 of the series.

1
2
3
4
5
6
7
8
9
10
11
try {
    System.out.println("Correct 1");
    foo();
    System.out.println("Correct 2");
    bar();
    System.out.println("Correct 3");
}
catch (Exception e) {
    System.out.println("Error");
}
System.out.println("End");

Given the above code, what will be printed in the following circumstances?

1.) foo() throws an exception
2.) bar() throws an exception
3.) no exceptions are thrown

Answers are provided after the jump.

1.) foo() throws an exception
If foo() throws an exception, the flow is immediately stopped at that call and jumps to the catch block. Realize that if there were multiple catch blocks, the catch block executed would depend on the type of exception thrown. The code inside of the catch block is executed and then flow resumes after the block. The result would be:

1
2
3
Correct 1
Error
End

2.) bar() throws an exception
This example follows the same explanation as for the above case. The result would be:

1
2
3
4
Correct 1
Correct 2
Error
End

3.) no exceptions are thrown
If no exceptions are thrown, the try block executes normally and the catch block is skipped entirely. The result would be:

1
2
3
4
Correct 1
Correct 2
Correct 3
End

Comments are closed.