Java

如何自定义Java异常并在trycatch中处理

小樊
83
2024-09-04 09:49:48
栏目: 编程语言

要自定义Java异常并在try-catch语句中处理,请按照以下步骤操作:

  1. 创建一个新的类,该类继承自Exception或其子类。通常,可以从RuntimeExceptionIOException等现有异常类派生。
public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}
  1. 在需要抛出自定义异常的地方使用throw关键字抛出异常。例如,在一个方法中检查输入参数是否有效,如果无效则抛出自定义异常。
public void checkInput(int input) throws CustomException {
    if (input < 0) {
        throw new CustomException("Invalid input: " + input);
    }
    // 其他代码
}
  1. 在调用此方法的地方使用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语句之后的代码。

0
看了该问题的人还看了