Custom Exceptions
Custom exceptions allow you to create your own exception classes to handle specific errors in your program. This tutorial will teach you how to define and use custom exceptions.
Creating a Custom Exception
To create a custom exception, extend the Exception
class:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
Throwing a Custom Exception
You can throw a custom exception using the throw
keyword:
public class Main {
public static void main(String[] args) {
try {
validate(10);
} catch (CustomException e) {
System.out.println("Caught the exception");
System.out.println(e.getMessage());
}
}
static void validate(int number) throws CustomException {
if (number < 20) {
throw new CustomException("Number is less than 20");
}
}
}
In this example, the validate
method throws a CustomException
if the number is less than 20.
Handling a Custom Exception
Handle a custom exception using a try-catch
block:
public class Main {
public static void main(String[] args) {
try {
validate(15);
} catch (CustomException e) {
System.out.println("Caught the custom exception");
System.out.println(e.getMessage());
}
}
static void validate(int number) throws CustomException {
if (number < 18) {
throw new CustomException("Age must be at least 18");
} else {
System.out.println("Valid age");
}
}
}
In this example, the validate
method throws a CustomException
if the age is less than 18.
Continue exploring our intermediate tutorials to learn more about Java programming.