Skip to main content

Java Custom Exceptions

Java exceptions cover almost all general exceptions that are bound to happen in programming. However, we sometimes need to supplement these standard exceptions with our own.

So java exceptions can be checked and unchecked exceptions.

Java Custom checked exception

To create a custom exception, we have to extend the java.lang.Exception class.


public class RamException extends Exception {
public RamException(String errorMessage) {
super(errorMessage);
}
}

we should add a java.lang.Throwable parameter to the constructor.
This way, we can pass the root exception to the method call

public RamException(String errorMessage, Throwable err) {
super(errorMessage, err);
}

Java Custom unchecked exception

To create a custom unchecked exception, we need to extend the java.lang.RuntimeException class,

public class RamException 
extends RuntimeException {
public RamException(String errorMessage, Throwable err) {
super(errorMessage, err);
}
}

Custom exceptions are very useful when we need to handle specific exceptions related to the business logic. When used properly, they can serve as a practical tool for better exception handling and logging.