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())
              }
          }
      }
      
    你所看得到的天才不过是在你看不到的时候还在努力罢了!
  • 相关阅读:
    An AODV Tutorial
    MFC去掉单文档的"无标题-"的方法
    win32 openss 编译
    ASP.NET实现RENREN SIG计算
    std::string str.c_str() const
    fopen
    curl with ssl support for win32
    VC++ utf8 Unicode GB2312 编码转换
    编码转换
    VirtualBox uuid冲突问题
  • 原文地址:https://www.cnblogs.com/heliusKing/p/10858832.html
Copyright © 2011-2022 走看看