阅读量:82
要自定义Java异常并在try-catch语句中处理,请按照以下步骤操作:
- 创建一个新的类,该类继承自
Exception或其子类。通常,可以从RuntimeException、IOException等现有异常类派生。
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
- 在需要抛出自定义异常的地方使用
throw关键字抛出异常。例如,在一个方法中检查输入参数是否有效,如果无效则抛出自定义异常。
public void checkInput(int input) throws CustomException {
if (input < 0) {
throw new CustomException("Invalid input: " + input);
}
// 其他代码
}
- 在调用此方法的地方使用try-catch语句来捕获和处理自定义异常。
public static void main(String[] args) {
MyClass obj = new MyClass();
try {
obj.checkInput(-5);
} catch (CustomException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
这样,当checkInput()方法抛出CustomException时,程序会捕获并处理该异常,然后继续执行try-catch语句之后的代码。