Home > DeveloperSection > Articles > Exception Handling in Java: Declaring Exceptions in Overriding Methods

Exception Handling in Java: Declaring Exceptions in Overriding Methods


Java Exception Handling  Java 
Ratings:
0 Comment(s)
 204  View(s)
Rate this:

Exception Handling in Java: Declaring Exceptions in Overriding Methods


Let’s recall the rules we learn from previous post about declaring exception in Overriding Methods.

When we override these methods, we must observe certain rules:


•An overriding method must throw exceptions of the same type as the exceptions being thrown by the overridden method.

•An overriding method may throw exceptions that are subclasses of the exceptions being thrown by the overridden method.

•An overriding method cannot throw a superclass exception of an exception declared by an overridden method.

•In case of an overridden method throwing multiple exceptions, an overriding method must throw a proper subset of exceptions thrown by the overridden method.                                                                                        

To explain these rules, we’ll look at a few code snippets. Here’s the first:

class WebBrowser {

                     public void makeConnection() throws IOException {

                     }

}

 

class HTMLWebBrowser extends WebBrowser {

                     public void makeConnection() throws ProtocolException {

                     }

}

 

class RichTextWebBrowser extends HTMLWebBrowser {

                     public void makeConnection() throws Exception {

                     }

}

 

 

•The HTMLWebBrowser class that inherits WebBrowser overrides the makeConnection method.

 

•This overridden method throws ProtocolException, which is a subclass of IOException. This satisfies the second rule in the list and is therefore permitted.

 

•The class RichTextWebBrowser, too, overrides the makeConnection method in its implementation. However, it tries to throw an Exception type, which violates the third rule and therefore won’t compile.

 

•This explains why earlier (in final re-throw post) I said that throwing the Exception type would not compile the code, causing us to use the final keyword in the catch block, which is a Java SE 7 feature.

 

To explain the other rules, let’s make some slight modifications to the earlier code snippet, as shown here:

class WebBrowser {

               public void makeConnection() throws IOException, RuntimeException {

              }

}

 

class HTMLWebBrowser extends WebBrowser {

                  public void makeConnection() throws ProtocolException, EOFException,

                                                                           ArithmeticException, SecurityException {

                 }

}

 

class RichTextWebBrowser extends HTMLWebBrowser {

                   public void makeConnection() throws ProtocolException, SecurityException {

                  }

}

 

•Now, the makeConnection method in the base class throws two types of exceptions: IOException and RuntimeException.


•The overridden makeConnection method in the HTMLWebBrowser class throws four different types of exceptions. All these are the subtypes of either IOException or RuntimeException, thus adhering to the second rule.


•The makeConnection method of RichTextWebBrowser overrides the corresponding method of HTMLWebBrowser, but throws only a subset of exception types thrown by the overridden method. This satisfies the fourth rule and would thus compile without errors.


•Also, if a superclass method throws no exceptions, neither can the subclass method. The situation stated here can be overcome with a simple trick. We have seen how to construct and throw a custom exception object. In situations where we are not allowed to throw a checked exception, we can wrap a checked exception into an object of RuntimeException and throw it to the caller. This is illustrated in the program here:


import java.net.*;

 

public class CustomBrowser {

                     public static void main(String[] args) {

                             HTMLWebBrowser app = new HTMLWebBrowser();

                             try {

                                      app.makeConnection();

                             } catch (Exception e) {

                                      System.out.println(e.getMessage());

                             }

                     }

}

 

class WebBrowser {

                     public void makeConnection() {

                     }

}

 

class HTMLWebBrowser extends WebBrowser {

                     public void makeConnection() throws RuntimeException {

                             try {

                                      URL url = new URL("http://www.oracle.com");

                             } catch (MalformedURLException e) {

                                      RuntimeException ae = new RuntimeException("Invalid url");

                                      ae.initCause(e);

                                      throw ae;

                             }

                     }

}

 

•The makeConnection method of the HTMLWebBrowser class knows that its code may generate an error at runtime; however, it would like its base class to take care of the error handling.


•The makeConnection method of the base class (WebBrowser) also does not process or throw an exception up the hierarchy.


•To overcome this problem, we can always create an object of RuntimeException in the overridden method, wrap the generated exception in it, and throw it up the hierarchy. The following three lines of code do this:

RuntimeException ae = new RuntimeException("Invalid url");

ae.initCause(e);

throw ae;

 

This trick works, and the compiler does not complain on the overridden method declaration. We may now process the custom exception object anywhere up the hierarchy. In our case, the exception is caught and processed in the main method.


Don't want to miss updates? Please click the below button!

Follow MindStick