Reputation: 8278
I wonder why it makes sense to have an empty try block followed by catching specific exception? Any thoughts?
try {
} catch (Exception e) {
// do nothing
}
Upvotes: 1
Views: 360
Reputation: 12524
Not everything that compiles should "make sense", as long as your code does not contain syntax and semantic errors it will compile and most likely even run.
The main idea is that every part of your code can potentially throw an exception. Try Catch
blocks do not add an additional overhead to your compiled code and thus there is no problem using them even for any code.
Upvotes: 2
Reputation: 24641
runtime exceptions are not type-checked and can be unpredictably thrown
Upvotes: 2
Reputation: 1499760
The idea is that unchecked exceptions can be thrown by any code, so if you're catching something which can catch an unchecked exception, the compiler doesn't check whether the code in the try
block can throw anything. In the special case where there really is no code in the try block, this is inappropriate - but it keeps the language simpler, and it's only a problem in completely bogus code which I wouldn't expect to show up in any real codebase. I guess there are similar situations where you're only doing things with primitives etc, but it really is an edge case. Most try blocks will contain code which could theoreically throw an unchecked exception.
If you try to catch a checked exception type which isn't thrown in the try
block, then the compiler will complain.
Upvotes: 7