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

javaobject oriented programmingprogramming更新于 2024/5/12 3:16:00

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

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

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

  • CustomException 类是自定义异常类,该类扩展了 Exception 类。
  • 创建一个局部变量消息,将异常消息本地存储在类对象中。
  • 我们将一个字符串参数传递给自定义异常对象的构造函数。构造函数将参数字符串设置为私有字符串消息。
  • toString() 方法用于打印出异常消息。
  • 我们只是在主方法中使用一个 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

相关文章