Exceptions in Java VIII: Creating Custom Exceptions

Custom Exceptions are user defined exceptions. These are exceptions that a programmer can define and use over and above the exceptions that Java already provides.

Defining and Using a Checked Exception

We continue with the Politician example that we discussed in previous lesson. We will write our own checked exception called PoliticianAbscondingException and will see how to use it.

Here is the Exception class –

Note that our custom exception is a checked exception because it extends from java.lang.Exception. Further, we want to deliver a custom message with our exception so that our client has better knowledge of the cause of the exception. Therefore, we override the constructor of Exception class and pass along the String to super.  Here is how we can use the custom exception in the Politician class –

The output of the above code is –

Note how we were able to print the exact cause of why justice could not served. This exactness in pin pointing the exact condition that prevails at runtime is the core benefit of custom exception.

Defining and Using an Unchecked (Runtime) Exception

As discussed in the previous lesson, a checked exception causes a lot of code bloat because of massive amounts of boilerplate code that needs to be written. We will repeat the same example as above with a runtime exception.

An unchecked exception class extends from RuntimeException as shown below-

Note that this is the same as the checked exception class except that it extends from RuntimeException.

This exception can now be used in our Politician class as follows –

The output of the above code is exactly what it was in the previous checked exception example –

The convenience afforded by the runtime exception is that now there is no throws clause for

Further, the client of this code is free to either use the try, catch block to catch an exception or propagate the exception as shown next –

The output of the above code is –

Note that the output in both cases is similar and affords the same advantages in both cases. The advantage of using runtime exception is flexibility and a more concise code.

Leave a comment

Your email address will not be published.