zoukankan      html  css  js  c++  java
  • java自定义异常类

    java自定义异常类

    1. MyException类

      //或者继承RuntimeException(运行时异常) 
      public class MyException extends Exception { 
      
        private static final long serialVersionUID = 1L; 
      
        // 提供无参数的构造方法
        public MyException() { 
        } 
      
        // 提供一个有参数的构造方法,可自动生成
        public MyException(String msg) { 
          super(msg);// 把参数传递给Throwable的带String参数的构造方法 
        } 
      
      } 
      

      查看Exception类的源码, 发现源码也就这么写的,继承后自定义的异常类也就成为了java异常体系的一部分

    2. 写一个Student类,手动抛出MyException

      class Student{
          private int id;
          // 该异常继承自Exception类,需要捕获或者向上抛出异常
          public void regist(int id) throws Exception {
              if ( id > 0){
                  this.id = id;
              }else{
                  // 手动抛出异常
                  throw new MyException("不能输入负数");
              }
          }
      }
      
    3. 测试类StudentTest

      public class StudentTest{
          public static void main(String args[]){
              try{
                  Student s = new Student();
                  s.regist(-1001);
                  // 对Student类throws的异常进行try-catch处理;
                  System.out.println(s);
              }catch (Exception e){
                  System.out.println(e.getMessage())
              }
          }
      }
      
    你所看得到的天才不过是在你看不到的时候还在努力罢了!
  • 相关阅读:
    JTAG的SWD接线方式
    Qt のEXecl
    人脸识别
    Qt实现基本QMainWindow主窗口程序
    Qt学习之路MainWindow学习过程中的知识点
    QT_FORWARD_DECLARE_CLASS
    标准的并发控制实现
    C++ DFS
    C# 互操作(一) 编写一个C++ COM组件
    Socket使用SOAP调用WCF
  • 原文地址:https://www.cnblogs.com/heliusKing/p/10858832.html
Copyright © 2011-2022 走看看