温馨提示×

java中怎么抛出自定义异常

小亿
249
2024-02-20 11:04:30
栏目: 编程语言

在Java中,我们可以通过编写自定义异常类来定义自己的异常类型,并在需要的时候抛出该异常。以下是一个简单的示例:

// 自定义异常类 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()); } } } 

在上面的示例中,我们创建了一个名为MyCustomException的自定义异常类,继承自Exception类,并在构造方法中传入异常信息。然后在Main类中通过throw new MyCustomException("这是我自定义的异常")语句来抛出自定义异常,最后在catch块中捕获并处理该异常。

0