zoukankan      html  css  js  c++  java
  • 异常处理----声明抛出异常/人工抛出异常

    声明抛出异常

    声明抛出异常是Java中处理异常的第二种方式

    如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这种异常,则此方法应显式地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。

    在方法声明中用 throws 子句可以声明抛出异常的列表,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。


    声明抛出异常举例:

    public void readFile(String file) throws FileNotFoundException {
      ……
      // 读文件的操作可能产生FileNotFoundException类型的异常
      FileInputStream fis = new FileInputStream(file);
      ..……
    }

    public class Test8_5 {
      public static void main(String[] args) {
        Test8_5 t = new Test8_5();
        try{
          t.readFile();
        }catch(IOException e){ }
      }
      public void readFile()throws IOException {
        FileInputStream in=new FileInputStream("myfile.txt");
        int b;
        b = in.read();
        while(b!= -1) {
          System.out.print((char)b);
          b = in.read();
        }
        in.close();
      }
    }

    重写方法声明抛出异常的原则

    重写方法不能抛出比被重写方法范围更大的异常类型

    public class A {
      public void methodA() throws IOException {
        ……
      }
    }
    public class B1 extends A {
      public void methodA() throws FileNotFoundException {
        ……
      }
    }
    public class B2 extends A {
      public void methodA() throws Exception { //error
        ……
      }
    }


     1 public class TestThrows {
     2     public static void main(String[] args) {
     3         try {
     4             test();
     5         } catch (Exception e) {
     6             e.printStackTrace();
     7         }
     8     }
     9     //1. 在 Java 中使用 throws 关键字声明抛出异常. 
    10     //2. throws 方法抛出的异常可以是方法中出现的异常的类型或其父类类型. 
    11     //3. throws 可以声明抛出多个异常, 多个异常使用 , 分割. 
    12     public static void test() throws FileNotFoundException, SQLException { 
    13         //4. 运行时异常不需要使用 throws 关键字进行显式的抛出. 
    14         int i = 10 / 0;
    15         System.out.println(i);
    16          
    17         //编译时异常
    18         InputStream fs = new FileInputStream("abc.txt"); 
    19         
    20         Connection connection = null;
    21         String sql = null;
    22         PreparedStatement ps = connection.prepareStatement(sql);
    23         
    24         byte [] buffer = new byte[fs.available()];
    25         fs.read(buffer);
    26         
    27         //要求异常处理是一致的,不能抛出比被重写方法范围更大的异常类型
    28         A a = new B();
    29         try {
    30             a.method();
    31         } catch (FileNotFoundException e) {
    32             e.printStackTrace();
    33         }
    34     }
    35 }
    36 
    37 class A {
    38     void method () throws FileNotFoundException {
    39     }
    40 }
    41 //5. 重写方法不能抛出比被重写方法范围更大的异常类型
    42 class B extends A {
    43 //    @Override
    44 //    void method() throws IOException {
    45 //    }
    46 }

    人工抛出异常


    Java异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出,也可根据需要人工创建并抛出


    首先要生成异常类对象,然后通过throw语句实现抛出操作(提交给Java运行环境)。
      IOException e =new IOException();
      throw e;
    可以抛出的异常必须是Throwable或其子类的实例。下面的语句在编译时将会产生语法错误:
      throw new String("want to throw");

    创建用户自定义异常类


    用户自定义异常类MyException,用于描述数据取值范围错误信息。用户自己的异常类必须继承现有的异常类。
    class MyException extends Exception {
      private int idnumber;
      public MyException(String message, int id) {
        super(message);
        this.idnumber = id;
      }
      public int getId() {
        return idnumber;
      }
    }

    使用用户自定义异常类

    public class Test8_6 {
      public void regist(int num) throws MyException {
        if (num < 0) {
          throw new MyException(“人数为负值,不合理”,3);
        }else {
          System.out.println("登记人数" + num );

        }
      }
      public void manager() {
        try {
          regist(100);
        } catch (MyException e) {
          System.out.print("登记失败,出错种类"+e.getId());
        }
        System.out.print("本次登记操作结束");
      }
      public static void main(String args[]){
        Test8_6 t = new Test8_6();
        t.manager();
      }
    }


     1 /**
     2  * 人工手动抛出异常:
     3  * 1. 创建一个异常类对象
     4  * 2. 在方法内部使用 throw 关键字把该异常类对象抛出去!
     5  * 
     6  * 自定义的异常类:
     7  * 1. 通常继承自 RuntimeException(可以继承 Exception)
     8  * 2. 自定义的异常类就是用来被人工抛出的!
     9  */
    10 public class TestThrow {
    11     public static void main(String[] args) {
    12         try {
    13             inputAge();
    14         } catch (Exception e) {
    15             System.out.println(e.getMessage()); 
    16         }
    17         
    18         System.out.println("end...");
    19     }
    20     
    21     /**
    22      * 输入年纪: 要求年纪必须在 15-30 之间, 超出 30 则年纪偏大
    23      */
    24     public static void inputAge(){
    25         Scanner sc = new Scanner(System.in);
    26         
    27         System.out.print("age=");
    28         int age = sc.nextInt();
    29         
    30         if(age > 30){
    31 //            System.out.println("年纪偏大.");
    32             throw new AgeTooLargeException("年纪偏大.");
    33         }
    34     }
    35 
    36     public static void test(){
    37         
    38         //1. 创建一个异常类对象
    39         RuntimeException ex = new RuntimeException();
    40         
    41         //2. 把异常类对象抛出去
    42         throw ex;
    43     }
    44 }
     1 //自定义的异常类: 1. 通常继承自 RuntimeException(可以继承 Exception)
     2 public class AgeTooLargeException extends RuntimeException{
     3 
     4     private static final long serialVersionUID = 1L;
     5 
     6     public AgeTooLargeException() {
     7     }
     8     
     9     public AgeTooLargeException(String msg) {
    10         super(msg); 
    11     }
    12 }
  • 相关阅读:
    造数--存储过程,循环
    一句话搞定python六剑客
    数据库基本操作--增删改查
    session与cookie区别与联系
    正则表达式中 group groups区别
    迭代总结(随时更新)
    postman抓包
    linux常用命令
    抓包
    jdk 11特性
  • 原文地址:https://www.cnblogs.com/justdoitba/p/7233637.html
Copyright © 2011-2022 走看看