Why do methods have to declare the exceptions they can throw?
Ans : The simple answer is that the Java language requires it; the more meaningful answer is that the language requires exception declarations because they enhance the usability and robustness of code as part of an API. The Java language requires that a method declare any checked exceptions that the method might throw. Whether an exception is checked or not depends on the exception’s class. As shown in Table 2.9, the base Throwable class splits into two main subclass branches, Error and Exception. All Exception subclasses are checked exceptions except for RuntimeException and its subclasses. Table 2.9: Checked Expections versus Unchecked Exceptions Class hierarchy under Throwable Checked? Throwable Error and its subclasses no Exception RuntimeException and its subclasses no all other Exception subclasses yes The intent of checked exceptions is that you declare exceptions as a meaningful part of your class’s programming interface. Together with a method’s return value, exceptions define
Related Questions
- We can declare methods that throw an exception (or error) of unknown type. Example (of method with type parameter in throws clause): interface Task< E extends Exception > { void run() throws E ; } Can such a method throw an object of the unknown exception (or error) type?
- Given a method that doesn declare any exceptions, can I override that method in a subclass to throw an exception?
- Why do methods have to declare the exceptions they can throw?