Explain Codes LogoExplain Codes Logo

How to create a custom exception type in Java?

java
exception-handling
best-practices
custom-exceptions
Nikita BarsukovbyNikita Barsukov·Jan 20, 2025
TLDR

Create a custom exception by extending Exception class:

public class MyException extends Exception { public MyException(String message) { super(message); } }

Trigger it with throw:

throw new MyException("Exceptionally exceptional");

In this way, you can convey specific information about your program's error conditions.

Crafting the custom exception design

When creating a custom exception, consider the nature of the error you're dealing with.

The fine line between checked and unchecked

Java categorizes exceptions into two categories: checked and unchecked. Checked exceptions are subclasses of the Exception class (excluding RuntimeException and its subclasses which falls under unchecked). The golden rule thumb says, use checked exceptions for recoverable conditions and unchecked exceptions for programming errors.

The art of constructor crafting

A well-designed custom exception should allow passing specific error messages or related information through its constructors:

public class BinaryDataNotFoundException extends Exception { // Every hero needs an origin story public BinaryDataNotFoundException() { super("Lost in the binary sea"); } // Optional backstory public BinaryDataNotFoundException(String message) { super(message); } }

Specificity vs reusability

Ensure that you create a specific, yet reusable custom exception for similar error conditions. Avoid bloating your codebase with one-off exceptions for each distinguishable error, this confuses maintainers and violates DRY principle.

Best practices for exception handling

Implement standard error handling practices when using your custom exception. This includes using descriptive error messages, avoiding empty catch blocks, and documenting when a method can throw an exception.

The essence of a good error message

In the realm of exceptions, having meaningful, actionable error messages is as important as having a map in an unfamiliar city.

throw new DataIntegrityViolationException("Houston, we have a problem: Object" + objectId + " has gone rogue.");

When to stick to the classics

When working with universal error conditions, it's more efficient to use built-in exceptions:

public void setAge(int age) { if (age < 0 || age > 150) { throw new IllegalArgumentException("Checked your ID pal, you're " + age + "! That's a Guinness World Record!"); } }

Extending RuntimeException for custom unchecked exceptions

Situations may arise where you need a quick fix for one-off error scenarios. In these cases, extend RuntimeException to make a custom exception:

public class ConfigurationError extends RuntimeException { public ConfigurationError(String message, Throwable cause) { super(message, cause); } }