The below picture shows that "Checked" and "Unchecked" Exceptions are subclasses of Exception
. I find it confusing that you need to catch an Exception
but you don't need to catch a RuntimeException
, which directly inherits from Exception
. Is there a reason that the devs didn't let us throw Exceptions without needing to catch them?
More specifically: Why can you ignore only RuntimeExceptions
and it's children? Why wasn't there a Class introduced called CheckedException extends Exception
and you only need to catch it and it's children?
The confusing part is, that you can throw everything below RuntimeException
without issue, but when you move up to Exception
in the hierarchy, you need to catch it at some point. This is confusing because "abstraction" normally works otherwise. The more you move up, the simpler and more meta everything gets. This is not the case here. The more you move up, the more you have to do (like, putting try/catch after reaching Exception
).
Catching Exception will catch both checked and runtime exceptions. Runtime exceptions represent problems that are a direct result of a programming problem, and as such shouldn't be caught since it can't be reasonably expected to recover from them or handle them. Catching Throwable will catch everything.
Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can). One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly.
The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions.
Runtime exceptions represent problems that are the result of a programming problem and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. With the Exceptions you must catch it explicitly because you can still do something to recover.
If Exception
was unchecked then you could implicitly cast checked exceptions to unchecked ones, which would mean that you could throw checked exceptions without catching them like:
public void f() {
Exception e = new IOException();
throw e;
}
and also with overriding methods, if you throw a more specific exception, you can add the requirement to catch the exception that wasn't in the superclass:
public void f() throws Exception {
}
...
@Override
public void f() throws IOException {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With