Working with inheritance and exceptions
When a class inherits from another class, it can override the methods in this other class. There are some special rules for dealing with the declared exceptions and overriding methods. It’s important to understand this to successfully override methods that declare exceptions.
Declaring exceptions in method signatures
When a method can throw a checked exception that isn’t dealt with in that method by a try-catch, it is declared in the method’s signature. We have just learned that this is done with the throws
keyword, followed by the exception type(s).
Here’s an example:
public void readFile(String filename) throws IOException { // Read file code }
The readFile
method’s signature declares that it can throw IOException
. When we extend the class that this method is in, we can override the readFile
method. There are some important rules for how to deal with exceptions that are...