-1

It is knows that Runtime excpetions should not be caught (usually), For example NullPointer.

But if I have a catch block that catches the general class - Exception (not recommended, I know) it will catch both checked and unchecked excpetions.

The thing I don't understand is this: One can catch only Runtime Excpetions by writing: catch(RuntimeException ex) but not only checked excpetions, why? (I mean, what is the logic behind this?)

Why there is no class called Checked Exception in Java that all checked excpetions will be derived from (just like RuntimeExcpetion) so I will be able to catch only those exceptions?

Tom Dinur
  • 99
  • 1
  • 9
  • From [Oracle](https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html): `checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses`. Should be easy enough to determine if an exception if a checked exception based upon that criteria. – mario_sunny Nov 04 '19 at 21:59
  • 2
    Who says you can't catch checked exceptions? Pretty sure `IOException` is a checked exception that can be caught. Also what do you mean that Runtime exceptions should not be caught? Where are you getting this information from? – smac89 Nov 04 '19 at 22:08
  • It's super easy to catch the checked exceptions - they're the ones that it says it throws. Just get your IDE to catch those. If they're not there, they won't be passing through there. – Evan Knowles Nov 04 '19 at 22:11
  • 1
    The logic is that for checked Exceptions, you know exactly which ones might get thrown since they need to be declared in the functions `throws` clause. For unchecked Exceptions, you don't have that list, so a catch-all makes much more sense. – daniu Nov 04 '19 at 22:15

1 Answers1

2

You could always rethrow the RuntimeExceptions:

try {
  //code that throws
} catch (Exception e) {
  if (e instanceof RuntimeException) throw (RuntimeException) e;
  //handle checked exceptions here
}

But I fail to think of a situation where that may be needed.

Catching all exceptions like this is typically done at the highest level in your code such that unexpected exceptions (a) don't crash your app and (b) can be handled (showing a message to the user or logging something for example). In that case you probably want to catch all exceptions, checked and unchecked.

assylias
  • 321,522
  • 82
  • 660
  • 783