温馨提示×

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

小樊
109
2024-09-04 09:49:48
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要自定义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语句之后的代码。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何自定义异常类型并在trycatch中抛出

0