Correct me if I'm wrong, but isn't the program not supposed to execute statements after the catch statement if there is an exception? I was under the impression that the only way to do that was to use a finally block.
I'm afraid you are wrong. The point of try-catch
is that we execute some code in the try
that might fail. If an exception is thrown, then we handle the failure in the catch
block, then carry on as normal (rather than propagating the exception to a higher level, possibly exiting the entire program), executing any further code after the catch block.
Code in a finally
block is executed regardless of whether an exception is thrown. This is used for closing resources (such as open files) that need to be cleaned up whatever happens.
If you want to skip everything after the exception is thrown, then there is no point handling the exception with try-catch
. You would be better off handling the exception at a higher level (though in your example you are already at the top level i.e. main
).