Creating Custom Exceptions in Java
In Java, we can create our own exception types by writing custom exception classes and throwing them when required. Here is a simple example:
// 自定义异常类
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
// 抛出自定义异常
public class Main {
public static void main(String[] args) {
try {
throw new MyCustomException("这是我自定义的异常");
} catch (MyCustomException e) {
System.out.println("捕获到自定义异常:" + e.getMessage());
}
}
}
In the example above, we created a custom exception class named MyCustomException that inherits from the Exception class. We passed the exception information in the constructor method. Then in the Main class, we used the statement throw new MyCustomException(“This is my custom exception”) to throw the custom exception. Finally, we caught and handled the exception in the catch block.