Java based learning summary (22) - Exception Handling

First, the concept of exceptions

  Refers to the abnormal run-error occurs, that is wrong in the future when the program starts execution of appearing . The most important observation wrong name and line number when an error occurs.

  

Copy the code
 1 package cn.javastudy.summary;
 2 
 3 public class TestEx{
 4     
 5     public static void main(String args[]){
 6         int arr[]={1,2,3};
 7         System.out.println(arr[2]);
 8         /**
 9          * 这里使用try……catch来捕获除以0产生的异常,其基本格式是:
10          * try{
11                 statements;//可能产生异常的语句
12                 ……
13             }
14             catch(Throwable-subclass e){//异常参数e
15                 statements;//异常处理程序
16                 ……
17             }
18          */
19         try{
20             System.out.println(arr[2]/0);
21         }catch(ArithmeticException ae){//这里是这个异常参数的类型声明,即声明这个异常是属于哪种类型的异常
22             System.out.println("系统正在维护中,请稍后!");
23             /**
24              * 这里使用printStackTrace()方法把这个错误的堆栈信息打印出来。
25              * 所谓的“错误堆栈信息”指的是这个错误有可能是上一个错误引起的,
26              * 而上一个错误又有可能是由另外一个错误引起的。到底是由哪个错误引起的,
27              * 把所有的错误信息全都打印出来就知道了。这种信息往往能给我们程序员调试错误的提示。
28              * 这些信息很有用,因此我们往往使用这个方法把错误信息打印出来。
29              * 默认打印错误提示信息采用的也是使用这种方法打印出来的
30              */
31             ae.printStackTrace();
32         }
33     }
34 }
Copy the code

Code running results:

  

summary:

  Exceptions are errors that occur during operation, after an error occurs during the run JAVA wrong way to handle this is to first catch will find the appropriate code to see if there is a catch to catch the exception, if catch exist, then JAVA will automatically jump go to catch handle the exception, if there is no catch, then JAVA will throw to put the error, and then print out the associated error message. Want to have to try to write when catching exceptions with catch, you can not try not catch, try writing which is likely to produce unusual statement, catch which is written when there is a run time exception handling try inside the statement.

  When this method declaration may specify methods may throw an exception type, use throw an exception is thrown, there is method behind the statement must go to capture anomalies that may occur throws declaration.

  

Second, the unusual classification

  

Third, abnormal capture and processing

  Five key Java exception handling: the try, the catch, a finally, the throw, throws

  

  

  

  

  When Exception caught will be easy to make a deal, even if it is an exception to this error message printed out, this is a good programming practice. If you do not deal with, that is to quietly hide the error, but the error still exists, but can not see it. This is a very dangerous programming practice, absolutely can not do that, there must be an exception to capture make a deal, it can not handle to put an exception is thrown, so that other methods to deal with. Anyway, it can not be captured after an abnormal but do not make the appropriate treatment, which is a very bad programming practice.

  任何方法往外抛能处理的异常的时候都有一种简单的写法:“throws Exception”,因为Exception类是所有能处理的异常类的根基类,因此抛出Exception类就会抛出所有能够被处理的异常类里了。使用“throws Exception”抛出所有能被处理的异常之后,这些被抛出来的异常就是交给JAVA运行时系统处理了,而处理的方法是把这些异常的相关错误堆栈信息全部打印出来。除了在做测试以外,在实际当中编程的时候,在main方法里抛Exception是一个非常不好的编程习惯,应该使用try……catch去捕获异常并处理掉捕获后的异常。不能直接在main方法里把Exception抛出去交给JAVA运行时系统出力就完事了,这是一种不负责任的表现。如果想把程序写得特别健壮,使用try……catch去捕获异常并处理掉捕获后的异常是必不可少的做法。

四、try...cath...finally语句

  4.1. try语句

  

  4.2. catch语句

  

  我们一般使用printStackTrace()这个方法来打印异常的信息,使用这个方法打印出来的是所有出错的信息,包括了使用getMessage()方法打印出来的信息。使用这个方法之前要new一个错误对象出来才能调用它。因为它是专属于某个错误对象里面的方法。

  4.3. finally语句

  

  4.4.异常简单测试

Copy the code
  1 package cn.javastudy.summary;
  2 
  3 import java.io.FileInputStream;
  4 import java.io.FileNotFoundException;
  5 import java.io.IOException;
  6 
  7 public class TestException {
  8     
  9     /**
 10      * 任何方法往外抛能处理的异常的时候都有一种简单的写法:“throws Exception”,
 11      * 因为Exception类是所有能处理的异常类的根基类,因此抛出Exception类就会抛出所有能够被处理的异常类里了。
 12      * 使用“throws Exception”抛出所有能被处理的异常之后,这些被抛出来的异常就是交给JAVA运行时系统处理了,
 13      * 而处理的方法是把这些异常的相关错误堆栈信息全部打印出来。
 14      * @throws Exception
 15      */
 16     void fn() throws Exception {
 17         
 18     }
 19     
 20     /**
 21      * 在知道异常的类型以后,方法声明时使用throws把异常往外抛
 22      * @param i
 23      * @throws ArithmeticException
 24      */
 25     void m1(int i)  throws ArithmeticException {
 26         
 27     }
 28     
 29     void m2(int i) {
 30         if (i == 0) {
 31             //这种做法就是手动抛出异常,使用“throw+new出来的异常对象”就可以把这个异常对象抛出去了。
 32             //这里是new了一个异常对象,在构建这个对象的时候还可以指定他相关的信息,如这里指明了异常信息“i不能等于0”
 33             //这个对象抛出去的时候使用getMessage()方法拿到的就是“i不能等于0”这种信息。
 34             throw new ArithmeticException("i不能等于0");
 35         }
 36     }
 37     
 38     /**
 39      * 正常情况下如果这里不写try……catch语句那么程序编译时一定会报错,
 40      * 因为这里有可能会产生两个个必须要处理的异常:FileNotFoundException和IOException。
 41      * 但由于在声明方法f()时已经使用throws把可能产生的这两个异常抛出了,
 42      * 所以这里可以不写try……catch语句去处理可能会产生的异常。
 43      * f()方法把抛出的异常交给下一个要调用它的方法去处理
 44      * @throws FileNotFoundException
 45      * @throws IOException
 46      */
 47     void f() throws FileNotFoundException, IOException {
 48         //这里有可能会产生FileNotFoundException异常
 49         FileInputStream fis = new FileInputStream("MyFile.txt");
 50         //这里有可能会产生IOException异常
 51         int b = fis.read();
 52         while (b != -1) {
 53             System.out.println((char)b);
 54             b = fis.read();
 55         }
 56     }
 57     
 58     /**
 59      * 在f2()方法里面调用f()方法时必须要处理f()方法抛出来的异常,
 60      * 当然,如果f2()方法也没有办法处理f()方法抛出来的异常,那么f2()方法也可以使用throws把异常抛出,
 61      * 交给下一个调用了f2()的方法去处理f()方法抛出来的异常。
 62      * 这里f2()调用f()方法时,选择不处理f()方法中可能抛出的异常,将异常继续抛出
 63      * @throws Exception
 64      */
 65     void f2() throws Exception {
 66         f();
 67     }
 68     
 69     /**
 70      * f3方法调用f方法捕获f()方法抛出的2个异常并进行处理
 71      */
 72     void f3() {
 73         try {
 74             f();
 75         } catch (FileNotFoundException e) {
 76             System.out.println(e.getMessage());//处理的方法是把错误信息打印出来
 77         } catch (IOException e) {
 78             e.printStackTrace();//处理的方法是使用printStackTrace()方法把错误的堆栈信息全部打印出来。
 79         }
 80     }
 81     
 82     public static void main(String[] args) {
 83         FileInputStream fis = null;
 84         try {
 85             fis = new FileInputStream("MyFile.txt");
 86             int b = fis.read();//这个有可能会抛出IOException异常
 87             while (b != -1) {
 88                 System.out.println((char)b);
 89                 b = fis.read();
 90             }
 91         } catch (FileNotFoundException e) {
 92             //使用catch捕获FileNotFoundException类异常的异常对象e。并让异常对象e自己调用printStackTrace方法打印出全部的错误信息
 93             e.printStackTrace();
 94         } catch (IOException e) {
 95             //再次使用catch捕获IOException类的异常对象e,并让异常对象e自己调用getMessage()方法将错误信息打印出来。
 96             System.out.println(e.getMessage());;
 97         }finally{
 98             try {
 99                 /**
100                  * 前面已经把一个文件打开了,不管打开这个文件时有没有错误发生,即有没有产生异常,最后都一定要把这个文件关闭掉,
101                  * 因此使用了finally语句,在finally语句里面不管前面这个文件打开时是否产生异常,在finally这里执行in.close()都能把这个文件关闭掉,
102                  * 关闭文件也有可能会产生异常,因此在finally里面也使用了try……catch语句去捕获有可能产生的异常。
103                  */
104                 fis.close();
105             } catch (IOException e) {
106                 e.printStackTrace();
107             }
108         }
109     }
110 }
Copy the code

五、声明并抛出异常

六、使用自定义异常

  

6.1. 自定义异常

Copy the code
 1 package cn.javastudy.summary;
 2 
 3 /**
 4  * 自定义的一个异常类MyException,且是从Exception类继承而来
 5  */
 6 public class MyException extends Exception {
 7 
 8     private int id;
 9 
10     /**
11      * 自定义异常类的构造方法
12      * @param message
13      * @param id
14      */
15     public MyException(String message,int id) {
16         super(message);//调用父类Exception的构造方法
17         this.id = id;
18     }
19     
20     /**
21      * 获取异常的代码
22      * @return
23      */
24     public int getId() {
25         return id;
26     }
27     
28 }
Copy the code

6.2.自定义异常测试

Copy the code
 1 package cn.javastudy.summary;
 2 
 3 import java.text.MessageFormat;
 4 
 5 public class TestMyException {
 6 
 7     //throws MyException,抛出我们自定义的MyException类的异常。
 8     public void regist(int num) throws MyException {
 9         if (num < 0) {
10             //使用throw手动抛出一个MyException类的异常对象。
11             throw new MyException("人数为负值,不合理", 1);
12         }
13         /**
14          * 注意:当我们抛出了异常之后,
15          * System.out.println(MessageFormat.format("登记人数:{0}",num));是不会被执行的。
16          * 抛出异常之后整个方法的调用就结束了。
17          */
18         System.out.println(MessageFormat.format("登记人数:{0}",num));
19     }
20     
21     public void manage() {
22         try {
23             regist(-100);
24         } catch (MyException e) {
25             System.out.println("登记失败,错误码:"+e.getId());
26             e.printStackTrace();
27         }
28         System.out.println("操作结束");
29     }
30     
31     
32     public static void main(String[] args) {
33         TestMyException t = new TestMyException();
34         t.manage();
35     }
36 
37 }
Copy the code

测试结果:

  

七、异常处理总结

  

  Develop good programming habits, do not mistake to eat out (that is, the practice of capturing not make the appropriate treatment after an abnormal, this approach is equivalent to hide a mistake, and mistakes can still actually still exists), but also Do not throw out the mistakes, we must be able to handle the process, we must not throw out process. The method of throwing out there are two, one is after knowing the type of exception, the use of the method declaration throws an exception when thrown out, and the other is thrown out manually, use "throw + exception object" is the equivalent of you to throw this exception object out, and then write a statement of the kind of method to throw an exception.

Reproduced in: https: //my.oschina.net/zhanghaiyang/blog/594356

Guess you like

Origin blog.csdn.net/weixin_33892359/article/details/92648696