try-catch-finally blocks
12 Feb 2016It’s always pleasant to learn something new about a language you’ve been using for a while. Turns out when you declare a try block, you don’t need a catch block. You ALWAYS need a catch OR a finally block, but the catch block is not required if you have a finally block. This is valid Java:
What is practical usage of this? If you wanted your method to catch an exception but let the method caller handle it, you could skip catching and re-throwing the exception in your method. That looks something like this:
This is a decently cool trick, but like variable shadowing in Java, it’s probably better to explicitly catch the exception and throw it because it makes your code more readable. But if you’re into exercising a language to make your code more difficult to read, try-finally away!