|Navigate Exceptions topic: )|
A checked exception is an exception that must be either caught or declared in a method where it can be thrown. For example, the
java.io.IOException is a checked exception. To understand what is a checked exception, consider the following code:
|Code section 6.9: Unhandled exception.
This code won't compile as it throws or can throw a checked exception without catching it or declare it. Two different modifications can resolve the situation: to catching it or to declare it by the
In the Java class hierarchy, an exception is a checked exceptions if it inherits from
java.lang.Exception, but not from
java.lang.RuntimeException. All the application or business logic exceptions should be checked exceptions.
It is possible that a method declares that it can throw an exception, but actually it does not. Still, the caller has to deal with it. The checked exception declaration has a domino effect. Any methods that will use the previous method will also have to handle the checked exception, and so on.
So the compiler for the Java programming language checks, at compile time, that a program contains handlers for all application exceptions, by analyzing each method body. If, by executing the method body, an exception can be thrown to the caller, that exception must be declared. How does the compiler know whether a method body can throw an exception? That is easy. Inside the method body, there are calls to other methods; the compiler looks at each of their method signature, what exceptions they declared to throw.
Why force exception handling?
This may look boring to the developer but it enforces him to think about all the checked exceptions and increase the code quality. This compile-time checking for the presence of exception handlers is designed to make the application developer life easier. To debug whether a particular thrown exception has a matching catch would be a long process. In conventional languages like C, and C++, a separate error handling debugging were needed. In java we can be sure that when an application exception is thrown, that exception somewhere in the program is handled. In C, and C++, that has to be tested. In Java that does not need to be tested, so the freed up time can be used for more meaningful testing, testing the business features.
What exceptions can be declared, when overriding a method
The checked exception classes specified after the
throws keyword are part of the contract between the implementer and user. An overriding method can declare the same exceptions, subclasses or no exceptions.
What exceptions can be declared, when implementing an Interface
When interfaces are involved, the implementation declaration must have a throws-clause that is compatible with the interface declarations.