Last active
September 7, 2016 14:16
-
-
Save HopefulLlama/9330e5d0f01a4cd0067e7f088d11b02a to your computer and use it in GitHub Desktop.
Exploration of the behaviour of nested try blocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To understand how nested
try
blocks work in Java, the above code has a two level deep of nestedtry
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 whichcatch
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.one
two
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 areturn
in the nestedcatch
to end the function early.