在Java中,我们可以通过编写自定义异常类来定义自己的异常类型,并在需要的时候抛出该异常
在Java中,我们可以通过编写自定义异常类来定义自己的异常类型,并在需要的时候抛出该异常。以下是一个简单的示例:
//自定义异常类
classMyCustomExceptionextendsException{
publicMyCustomException(Stringmessage){
super(message);
}
}
//抛出自定义异常
publicclassMain{
publicstaticvoidmain(String[]args){
try{
thrownewMyCustomException("这是我自定义的异常");
}catch(MyCustomExceptione){
System.out.println("捕获到自定义异常:"+e.getMessage());
}
}
}
在上面的示例中,我们创建了一个名为MyCustomException
的自定义异常类,继承自Exception
类,并在构造方法中传入异常信息。然后在Main
类中通过thrownewMyCustomException("这是我自定义的异常")
语句来抛出自定义异常,最后在catch
块中捕获并处理该异常。
版权声明
本文仅代表作者观点,不代表博信信息网立场。