Explain Codes LogoExplain Codes Logo

How to create custom exceptions in Java?

java
custom-exceptions
exception-handling
java-best-practices
Alex KataevbyAlex Kataev·Oct 5, 2024
TLDR

Custom exceptions in Java are crafted by extending Exception or its derivatives and are thrown using custom constructors tailored for specific messages or causes. As an example:

// Creating a custom exception public class UserNotFoundException extends Exception { public UserNotFoundException(String userId) { super("User with ID " + userId + " not found. User might be enjoying vacation."); } }

This custom exception may be thrown as:

// Throwing a custom exception throw new UserNotFoundException("Matrix42");

This encapsulates the core practice of creating and hurling a custom exception.

Nitty-Gritty of Custom Exceptions

Custom Exception: Use Cases

  • Unique error situations: Diseases need specific treatments!
  • Meaningful communication: Talk to developers in a language they understand
  • Error categorization: Classify errors for better handling

Designing Custom Exceptions

Constructors

Holmes, "The Game is Afoot!"

  1. Default constructor: public MyException() {}
  2. Message constructor: public MyException(String msg) { super(msg); }
  3. Cause constructor: public MyException(Throwable cause) { super(cause); }
  4. Message and cause constructor: public MyException(String msg, Throwable cause) { super(msg, cause); }

These constructors are essential utilities in your Exception Toolkit.

Additional Methods

It's Elementary, my dear Watson!. Add helper methods that provide more context to the error such as error codes, recovery tips, etc.

Error Propagation

Is your error a checked or unchecked exception? Checked exceptions "Knock Knock!" (declare me!), unchecked exceptions "Ninja mode!" (no need to declare or catch).

RuntimeException and Exception

Extend RuntimeException for coding issues. Exception is more for recoverable conditions. Just remember, Exception is akin to Monroe's mole: It always catches the attention!

Few More Ins and Outs of Custom exceptions

  • Use custom messages when throwing an exception, like explaining which rule the user broke.
  • Unchecked exceptions should extend RuntimeException. It's like parking ticket, it doesn't warrant you to "Stop! Hammer Time!" and handle it.
  • Avoid the temptation of catching or throwing java.lang.Error and java.lang.Throwable. Their scariest thing is their names.
  • java.lang.Throwable - The Godfather of all exceptions and errors in Java. Respect the Hierarchy!

Exception Handling Recipes

Graceful Degradation

When everything's on fire in your program, maintain a cool face; Log everything for future CSI and keep the show running.

try { performRiskyOperation(); } catch (RiskyOperationException e) { logError(e); apologizeProfuselyToUser(); }

Fail-Fast

In case of unrecoverable errors, fail loudly and fast. Your program is not a Ninja to hide exceptions.

public void updateBankBalance(String accountId, BankUpdate bankUpdate) { if (accountId == null || bankUpdate == null) { throw new IllegalArgumentException("Account ID and update must not be null, unless you like free money"); } // Run the update... }

Avoiding Monsters in your Closet (Anti-patterns)

You don't want to find Loch Ness monster hiding in your code, do you?

  • Do not swallow exceptions - Every exception is a signal, not a meal.
  • Do not catch Godzilla-size exceptions (like Exception, Error, Throwable) unless serving them again.
  • Proper context in messages - Give enough scoop for troubleshooting, but avoid spilling state secrets.
  • Catching Throwable is usually a bad idea. It's like trying to catch Thor's mjolnir, doesn't end well.

Going the Extra Mile

It's all about context and code hygiene!

  • Defining custom exceptions with limited access (package-private) encourages encapsulation and keeps your API neat and clean.
package com.example.robo; class RoboSkynetRevoltException extends Exception { // SkyNet went sentient, run! }
  • Sometimes, standard exceptions hit the nail right on the head. Use them when they suffice.