How are exceptions defined in Java?
In Java, exceptions can be defined in two ways:
- Outlier
- An anomaly
- Anomaly
public class CustomException extends Exception {
// 自定义属性和方法
@Override
public String getMessage() {
// 重写getMessage()方法
return "自定义异常信息";
}
}
- Something that can be thrown.
- Something that can be thrown or tossed.
public class CustomException implements Throwable {
// 实现接口中的方法
}
When using custom exceptions, you can throw an exception object using the throw keyword, for example:
public void someMethod() throws CustomException {
// 抛出自定义异常
throw new CustomException();
}
When calling this method, any exceptions that occur can be caught and handled using a try-catch block. For example:
try {
someMethod();
} catch (CustomException e) {
// 处理异常
e.printStackTrace();
}