Java Custom Exceptions – Create and Handle Your Own Exceptions


Learn how to create custom exceptions in Java by extending Exception or RuntimeException, throw them, and handle them to implement robust business logic and error handling.

Custom Exceptions in Java – Complete Detailed Tutorial

Sometimes, built-in exceptions are not enough for your application.

Java allows creating custom exceptions for specific business logic or application rules.

1. Creating a Custom Exception

  1. Extend Exception → for checked exceptions (must be handled)
  2. Extend RuntimeException → for unchecked exceptions (optional handling)

Syntax:


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

2. Example – Checked Custom Exception


class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}

class Test {
void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18 or older");
} else {
System.out.println("Access granted");
}
}
}

public class Main {
public static void main(String[] args) {
Test t = new Test();
try {
t.checkAge(15);
} catch (AgeException e) {
System.out.println("Custom Exception caught: " + e.getMessage());
}
}
}

Output:


Custom Exception caught: Age must be 18 or older

3. Example – Unchecked Custom Exception


class NegativeNumberException extends RuntimeException {
NegativeNumberException(String message) {
super(message);
}
}

public class Main {
static void checkNumber(int num) {
if (num < 0) {
throw new NegativeNumberException("Negative numbers are not allowed");
} else {
System.out.println("Number is valid: " + num);
}
}

public static void main(String[] args) {
checkNumber(-5);
}
}

Output:


Exception in thread "main" NegativeNumberException: Negative numbers are not allowed

Explanation:

  1. Unchecked exceptions do not require try-catch
  2. Program may terminate if unhandled

4. Advantages of Custom Exceptions

  1. Represent application-specific errors
  2. Improve readability and maintainability
  3. Allow more precise exception handling
  4. Useful in business logic validation

5. Key Points

  1. Checked custom exceptions: extend Exception, must be caught or declared
  2. Unchecked custom exceptions: extend RuntimeException, optional handling
  3. Use super(message) to pass custom error message
  4. Helps create meaningful exception messages