Java 自定义异常(Exception)

1,311 阅读1分钟
  • 自定义格式

    public class 异常类名 extends Exception {
      无参构造
      带参构造
    }
    
  • 自定义案例

    public class ScoreException extends Exception {
      // 无参构造
      public ScoreException() {}
      // 带参构造
      public ScoreException(String message) {
        // 异常错误消息
        super(message);
      }
    }
    
  • 使用

    public class test {
      public static void main(String[] args) {
        try {
          // 调用异常代码
          checkScore(-1);
        } catch (Exception e) {
          // 输出错误
          System.out.println(e); // ScoreException: 分数只能在 0~120 之间
          System.out.println(e.getMessage()); // 分数只能在 0~120 之间
          /*
            // 在命令行打印异常信息在程序中出错的位置及原因
            e.printStackTrace();
            // 输出
            ScoreException: 分数只能在 0~120 之间
              at test.checkScore(test.java:19)
              at test.main(test.java:7)
          */
        }
      }
    
      // 检查分数
      public static void checkScore(int score) throws ScoreException {
        if (score < 0 || score > 120) {
          throw new ScoreException("分数只能在 0~120 之间");
        } else {
          System.out.println("分数正常");
        }
      }
    }