Custom Exceptions in Java

In this post we will provide an example of how to create custom exceptions in Java. The examples will include both checked  and unchecked exceptions.

Difference between checked and unchecked exceptions:

  • Checked exceptions: A checked exception extends the Exception class. Throwing a checked exception means you will need to declare it on the method signature. The client calling the method will be forced to handle the exception either via try-catch block or re-throwing the exception. Examples of checked exceptions include: FileNotFoundException and IOException
  • Unchecked exceptions: A unchecked exception extends the RuntimeException class. Throwing an unchecked exception means you don’t need to declare it on the method signature. The client calling the method will not be forced to handle the exception. Examples of unchecked exceptions include: NullPointerException and IllegalArgumentException

Custom Exceptions in Java:

1. Checked exception example:

Below is our checked exception, as you can see it extends the Exception class.

The utility class below defines a method findByName() which throws an exception when the user is not found.

A client calling the method findByName() will be forced by the compiler to handle the thrown exception as you can see from the code sample below.

 

2. Unchecked exception example:

Below is our unchecked exception, as you can see it extends the RuntimeException class.

The utility class below has a method findByName() which throws a unchecked exception when the user is not found.

A client calling the method findByName() will not be forced by the compiler to handle the thrown exception. However, if the exception is not handled, it will go up the stack until it is handled. If not, then that thread will die.

I hope this post has helped you understand how to create a checked and an unchecked exception.

Similar posts:

  1. String to Integer conversion
  2. Convert Byte array to String
  3. How to create a Thread in Java
  4. How to initialise an array in Java

References:

  1. Java Exception API Documentation
  2. Java RuntimeException API Documentation

Leave a Reply