← Back to Chapters

Java Custom Exceptions

⚠️ Java Custom Exceptions

? Quick Overview

Custom Exceptions in Java allow developers to create their own exception classes to represent specific error conditions in an application. They improve code readability, error handling clarity, and make debugging easier.

? Key Concepts

  • Custom exceptions extend Exception or RuntimeException
  • Checked vs Unchecked custom exceptions
  • Used to represent application-specific errors
  • Can include custom messages and logic

? Syntax & Theory

To create a custom exception, define a class that extends Exception (checked) or RuntimeException (unchecked). Provide constructors to pass error messages to the parent class.

? Code Example — Creating Custom Exception

? View Code Example
// Custom checked exception definition
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

? Code Example — Using Custom Exception

? View Code Example
// Demonstrates throwing and catching a custom exception
class TestAge {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above");
}
System.out.println("Valid age");
}

public static void main(String[] args) {
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}

? Live Output / Explanation

Output

Age must be 18 or above

The custom exception is thrown when the age is below 18. The catch block handles it gracefully and displays a meaningful message.

? Interactive Simulator

Enter an age below to simulate the Java logic in real-time. If you enter less than 18, the simulator will "throw" and "catch" the custom exception.

// Console output will appear here...

✅ Tips & Best Practices

  • Use meaningful exception class names
  • Prefer checked exceptions for recoverable conditions
  • Always include descriptive error messages
  • Group related exceptions in the same package

? Try It Yourself

  • Create a custom exception for insufficient balance
  • Modify it to include an error code
  • Convert it into an unchecked exception