Guide to Create Custom Exceptions


This guide walks you through how to create custom exceptions in your Java projects.

What will we learn?

  1. Steps to create custom exceptions
  2. How to create checked custom exceptions with examples?
  3. How to create an unchecked custom exception with examples?
  4. More examples
Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable).
In bigger applications, most of the cases we need custom exceptions for representing business exceptions which are, at a level higher than technical exceptions defined by JDK. 
Below are the examples for custom exceptions:
  • InvalidAgeException
  • ResouceNotFoundException
  • BadRequestException
  • UnauthorizedRequestException etc.

Writing your own exception class

Here are the steps create a custom exception:
  • Create a new class whose name should end with Exception like ClassNameException. This is a convention to differentiate an exception class from regular ones.
  • Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.
  • Create a constructor with a String parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message. In Java, there are two types of exceptions – checked and unchecked exception.
Here’s the summary :
Checked Exceptions – Extends java.lang.Exception, for the recoverable condition, need try-catch to handle exception explicitly, compile error.
Unchecked Exceptions – Extends java.lang.RuntimeException, for the unrecoverable condition, like programming errors, no need try-catch, a runtime error.
Let's create a custom exception named ResourceNotFoundException. Generally, ResourceNotFoundException custom exception thrown by service layer when resource requested not found.
Now, we will discuss how to create checked and unchecked custom exceptions with examples.

Custom Checked Exception

If the client is able to recover from the exception, make it a checked exception. To create a custom checked exception extends java.lang.Exception
public class ResourceNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;

    public ResourceNotFoundException(Object resourId) {
        super(resourId != null ? resourId.toString() : null);
    }
}
How to use ResourceNotFoundException custom exception in applications?
public class TestResourceNotFoundException {
    public static void main(String[] args) throws ResourceNotFoundException {
         ResourceManager manager = new ResourceManager();
         manager.getResource(0);
    }
}

class Resource {
    private int id;

    public Resource(int id) {
        super();
        this.id = id;
    }
}

class ResourceManager {
    public Resource getResource(int id) throws ResourceNotFoundException {
        if (id == 10) {
             new Resource(id);
        } else {
             throw new ResourceNotFoundException("Resource not found with id ::" + id);
        }
        return null;
    }
}

class ResourceNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;

    public ResourceNotFoundException(Object resourId) {
        super(resourId != null ? resourId.toString() : null);
    }
}
Output :
Exception in thread "main" com.ramesh.corejava.devguide.exceptions.customexceptions.ResourceNotFoundException: Resource not found with id ::0
 at com.ramesh.corejava.devguide.exceptions.customexceptions.ResourceManager.getResource(TestResourceNotFoundException.java:26)
 at com.ramesh.corejava.devguide.exceptions.customexceptions.TestResourceNotFoundException.main(TestResourceNotFoundException.java:6)

Custom Unchecked Exception

If the client cannot do anything to recover from the exception, make it an unchecked exception. To create a custom unchecked exception extends java.lang.RuntimeException
public class BaseRuntimeException extends RuntimeException {
  
    private static final long serialVersionUID = 1L;

    private int statusCode = 500;

    public BaseRuntimeException() {
        super();
    }

    public BaseRuntimeException(String message) {
        super(message);
    }

    public BaseRuntimeException(BaseException be) {
        super(be.getMessage(),be);
        this.statusCode = be.getErrorCode();
    }

    public BaseRuntimeException(Throwable t) {
        super(t.getMessage(),t);
    }

    public BaseRuntimeException(String message, Throwable t) {
        super(message, t);
    }

    public BaseRuntimeException(int status, String message, Throwable t) {
        super(message, t);
        this.statusCode = status;
    }

    public BaseRuntimeException(String message, Throwable t,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, t, enableSuppression, writableStackTrace);
    }

    public int getStatusCode() {
        return statusCode;
    }
}
How to use BaseRuntimeException custom exception in applications.
public class TestRunTimeException {
    public static void main(String[] args) {
        List<String> data = new ArrayList<>(Collections.nCopies(100, "Ramesh"));
        processData(data);
    }
 
    public static void processData(List<String> data){
        if(data.size() > 50){
             throw new BaseRuntimeException("Image file size con't exceed :: " + 10000000);
        }
    }
}
Output:
Exception in thread "main" com.ramesh.corejava.devguide.exceptions.customexceptions.BaseRuntimeException: Image file size con't exceed :: 10000000
 at com.ramesh.corejava.devguide.exceptions.customexceptions.TestRunTimeException.processData(TestRunTimeException.java:15)
 at com.ramesh.corejava.devguide.exceptions.customexceptions.TestRunTimeException.main(TestRunTimeException.java:10)

More Examples

Few Custom Exceptions that I personally have been using in my day-to-day project work.

BadRequestException Custom Exception

BadRequestException custom exception is thrown by the service layer when a request parameter is wrong.
public class BadRequestException extends Exception {
    private static final long serialVersionUID = 1L;

    public BadRequestException() {
        super();
    }

    public BadRequestException(String message) {
        super(message);
    }

    public BadRequestException(String message, Throwable t) {
        super(message, t);
    }

    public BadRequestException(Throwable t) {
        super(t);
    }
}

ResourceNotFoundException Custom Exception

ResourceNotFoundException custom exception is thrown by service layer when resource requested not found.
public class ResourceNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;

    public ResourceNotFoundException(Object resourId) {
        super(resourId != null ? resourId.toString() : null);
    }
}

UnauthorizedRequestException Custom Exception

UnauthorizedRequestException custom exception is thrown by service layer when a request parameter is wrong or user is unauthorized.
public class UnauthorizedRequestException extends Exception {
    private static final long serialVersionUID = 1L;

    public UnauthorizedRequestException(String message) {
        super(message);
    }
}

Comments