Java Custom Exception Example
In this example we will look briefly at the basics of Exception
, in Java Programming Language. We will also see, how to create a custom Exception
Class.
1. Basics of Exception
As per oracle docs, An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.
In laymen terms, when a condition occurs, in which the routine is not sure how to proceed in an ordinary way it creates an object of exception and hands it over to the runtime system to find an appropriate handler for the exception object. In case, the runtime system does not find an appropriate handler in the call hierarchy the runtime system terminates.
The exceptions have java.lang.Throwable
as their superclass.The three main categories of Exceptional conditions are :
- Error(represented by
java.lang.Error
and its sub-classes) - Checked Exception(represented by direct subclasses of
java.lang.Exception
exceptjava.lang.RuntimeException
) - Unchecked or Runtime Exceptions (represented by
java.lang.RuntimeException
and its sub-classes)
Errors : Errors denote serious abnormal condition with the application like OutOfMemoryError
or VirtualMachineError
. Any reasonable application should not try to recover from such a condition.
Runtime Exception/Unchecked Exception : These types of exceptions usually indicate programming errors like NullPointerException
or IllegalArgumentException
. The application may or may not choose to recover from the condition.
Checked Exception : An application is supposed to catch these types of exceptions and recover reasonably from them. Examples include FileNotFoundException
and ParseException
.
2. Creating custom Exception
The first thing before creating a custom exception, the developer should be able to justify the creation. As per Java Docs, You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else’s.
- Do you need an exception type that isn’t represented by those in the Java platform?
- Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
- Does your code throw more than one related exception?
- If you use someone else’s exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?
Now, that you are sure that you really do want a create a custom Exception class we will begin writing the actual program.
To create a custom checked exception, we have to sub-class from the java.lang.Exception
class. And that’s it! Yes, creating a custom exception in java is simple as that!
public class CustomException extends Exception{}
Sometimes though, the CustomException
object will have to be constructed from another exception. So its important that we create a constructor for such a scenario.
So a more complete class would be as below :
CustomException.java:
package com.javacodegeeks.examples.exception; public class CustomException extends Exception { private static final long serialVersionUID = 1997753363232807009L; public CustomException() { } public CustomException(String message) { super(message); } public CustomException(Throwable cause) { super(cause); } public CustomException(String message, Throwable cause) { super(message, cause); } public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
2.1 Testing the custom Exception :
CustomExceptionTest.java:
package com.javacodegeeks.examples.exception; public class CustomExceptionTest { public static void main(String[] args) { try { testException(null); } catch (CustomException e) { e.printStackTrace(); } } public static void testException(String string) throws CustomException { if(string == null) throw new CustomException("The String value is null"); } }
Similarly, an unchecked exception can be created by sub-classing from the java.lang.RuntimeException
Class.
public class CustomException extends RuntimeException{...}
3. Points to note
- An unchecked exception should be preferred to a checked exception. This will help programmes to be free of unnecessary
try..catch blocks
. - Exceptions are abnormal conditions, and as such should not be used for controlling the flow of execution of the programmes(as demonstrated by example below).
try { for (int i = 0;; i++) { System.out.println(args[i]); } } catch (ArrayIndexOutOfBoundsException e) { // do nothing }
- A
catch block
should not be empty as shown in the example above. Such exceptions are very difficult to track, since there is no logging. - The name of a custom exception class should end with Exception. It improves the readability of the code. Instead of naming the class InvalidSerial, the class should be named InvalidSerialException.
- When using ARM/try-with-resources blocks, if exception gets suppressed by the try-with-resources statement, we can use
Throwable#getSuppressed()
method.
4. Closing Words
Here,we tried to understand the basics of exception and how to create a custom exception of our own. We learned the best practices while creating a custom exception class and also how to handle an exception in a reasonable manner.