In Java, you can create custom exceptions to handle specific errors or unexpected events in your code. Custom exceptions are subclasses of the `Exception` class or one of its subclasses. Here are some basics of creating and using custom exceptions in Java:
1. Creating a custom exception: To create a custom exception, you can create a new subclass of the `Exception` class or one of its subclasses. For example:
public class InvalidInputException extends Exception { public InvalidInputException(String message) { super(message); } }
Here, a new `InvalidInputException` is created as a subclass of the `Exception` class. The constructor takes a message describing the error.
2. Throwing a custom exception: Once you have created a custom exception, you can throw it using the `throw` keyword. For example:
public void validateInput(String input) throws InvalidInputException { if (input == null || input.isEmpty()) { throw new InvalidInputException("Input cannot be null or empty"); } // validate other input conditions here }
Here, an `InvalidInputException` is thrown if the input is null or empty.
3. Catching a custom exception: When a custom exception is thrown, it can be caught and handled using a try-catch block. For example:
try { validateInput(null); } catch (InvalidInputException e) { System.err.println("Error: " + e.getMessage()); }
Here, the `validateInput` method is called with a null input, which throws an `InvalidInputException`. The catch block catches the exception and prints an error message.
Creating custom exceptions in Java is an important part of writing robust and reliable code. By creating custom exceptions to handle specific errors or unexpected events, you can write more maintainable code that is easier to read and understand.