How do you create custom exceptions in Java?
To create a custom exception in Java, you need to extend the Exception
class or one of its subclasses like RuntimeException
. Here’s a simple example:
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
You can then throw it like any other exception:
throw new MyCustomException("Something went wrong!");
This way, you can define your own error conditions in your program.