在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块中捕获并处理该异常。


