我们如何在Java中创建自定义异常?

有时需要根据应用程序需求开发有意义的异常。我们可以通过扩展Java中的Exception类来创建自己的异常

Java中用户定义的异常也称为自定义异常。

使用示例创建自定义异常的步骤

  • CustomException类是自定义异常类,该类是Exception类的扩展。

  • 创建一个本地变量消息以将异常消息本地存储在类对象中。

  • 我们正在将字符串参数传递给自定义异常对象的构造函数。构造函数将参数字符串设置为私有字符串消息。

  • toString()方法用于打印出异常消息。

  • 我们只是在main方法中使用一个try-catch块抛出一个CustomException,并观察在创建自定义异常时如何传递字符串。在catch块内部,我们正在打印消息。

示例

class CustomException extends Exception {
   String message;
   CustomException(String str) {
      message = str;
   }
   public String toString() {
      return ("Custom Exception Occurred : " + message);
   }
}
public class MainException {
   public static void main(String args[]) {
      try {
         throw new CustomException("This is a custom message");
      } catch(CustomException e) {
         System.out.println(e);
      }
   }
}

输出结果

Custom Exception Occurred : This is a custom message