Skip to content

Instantly share code, notes, and snippets.

@HopefulLlama
Last active September 7, 2016 14:16
Show Gist options
  • Save HopefulLlama/9330e5d0f01a4cd0067e7f088d11b02a to your computer and use it in GitHub Desktop.
Save HopefulLlama/9330e5d0f01a4cd0067e7f088d11b02a to your computer and use it in GitHub Desktop.
Exploration of the behaviour of nested try blocks
public class NestedTry {
public static void main(String[] args) {
try {
try {
Long one = Long.parseLong("1");
} catch(NumberFormatException e) {
System.out.println("First block!");
}
Long two = Long.parseLong("2");
} catch(NumberFormatException nfe) {
System.out.println("Second block!");
}
}
}
@HopefulLlama
Copy link
Author

HopefulLlama commented Sep 7, 2016

To understand how nested try blocks work in Java, the above code has a two level deep of nested try blocks. Both are simply parsing a string into a Long, and printing a message given the exception. The content of the message acts as a marker to easily show which catch block is being executed.

By changing the input to the parseLong method, we can force exceptions to be thrown in different areas, and observe the results. The table below outlines the results.

Test Number Input to one Input to two Output
1 "1" "2"
2 "swag" "2" "First block!"
3 "1" "swag" "Second block!"
4 "swag" "swag" "First block!" & "Second block!"

What is important to note is that in test number 2, the exception from the nested block, did not bubble up to the outer block.

In test number 4, we see two outputs, as the code continues to execute, after handling each exception in the respective catch blocks. If this is undesired, it is possible to use a return in the nested catch to end the function early.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment