Home  >  Article  >  Java  >  Detailed introduction to exceptions in JAVA

Detailed introduction to exceptions in JAVA

零下一度
零下一度Original
2017-07-17 09:46:251383browse

1. Introduction to exceptions

Exception:

Exception: It is abnormal. Abnormal conditions that occur when the program is running. In fact, it is a problem in the program. This problem is described according to object-oriented ideas and encapsulated into objects. Because the occurrence of a problem has multiple attribute information such as the cause of the problem, the name of the problem, and the description of the problem. When multi-attribute information appears, the most convenient way is to encapsulate the information. Exceptions are Java's object encapsulation of problems according to object-oriented thinking. This makes it easier to operate and deal with problems.

There are many kinds of problems, such as out-of-bounds corner markers, null pointers, etc. Just categorize these issues. Moreover, these questions have common content, such as: each question has a name, as well as problem description information and the location of the problem, so it can be continuously extracted. An abnormal system was formed.

#What is the exception system in Java?

#1. All abnormal classes in Java inherit from the Throwable class. Throwable mainly includes two major categories, one is the Error class and the other is the Exception class;

  

2. The Error class includes Virtual machine error And thread deadlock, once an Error occurs, the program will completely hang , which is called program terminator;

 

3.Exception class, also known as "exception". Mainly refers to problems with coding, environment, and user operation input. Exceptions mainly include two categories, unchecked exceptions (RuntimeException) and checked exceptions (some other exceptions)

 

4.RuntimeException exceptions mainly include the following four exceptions (in fact, there are many other exceptions, not listed here): Null pointer exception, array subscript out-of-bounds exception, type conversion exception, arithmetic exception . RuntimeException exceptions will be automatically thrown and automatically captured by the java virtual machine (Even if we do not write an exception capture statement, an error will be thrown during runtime!!). Most of the cases where such exceptions occur are in the code itself. Problems should be solved logically and the code should be improved.

 

5. Check for exceptions. There are various reasons for this exception, such as the file does not exist, or there is a connection error, etc. Unlike its "brother" RuntimeException, we must manually add a capture statement to the code to handle the exception . This is also the exception object we mainly handle when learning java exception statements.

 


2. try-catch-finally statement

(1) try block: is responsible for catching exceptions , once try If an exception is found, control of the program will be transferred to the exception handler in the catch block.

 [The try statement block cannot exist independently and must be co-existing with the catch or finally block]

(2) Catch block: How to deal with it? For example, issue warnings:Prompts, check configuration, network connection, record errors, etc.. After executing the catch block, the program jumps out of the catch block and continues to execute the following code.

Notes on writing catch blocks: Exception classes processed by multiple catch blocks should be handled in a manner of first catching the subclass and then catching the parent class, because the exception will be [handled nearby] (from the above from below).

(3)finally:The code that is finally executed is used to close and release resources.

============================================== ===========================

The syntax format is as follows:

try{//一些会抛出的异常}catch(Exception e){//第一个catch//处理该异常的代码块}catch(Exception e){//第二个catch,可以有多个catch//处理该异常的代码块}finally{//最终要执行的代码}

当异常出现时,程序将终止执行,交由异常处理程序(抛出提醒或记录日志等),异常代码块外代码正常执行。 try会抛出很多种类型的异常,由多个catch块捕获多钟错误

多重异常处理代码块顺序问题先子类再父类(顺序不对编译器会提醒错误),finally语句块处理最终将要执行的代码。

=======================================================================

接下来,我们用实例来巩固try-catch语句吧~

先看例子:

 1 package com.hysum.test; 2  3 public class TryCatchTest { 4     /** 5      * divider:除数 6      * result:结果 7      * try-catch捕获while循环 8      * 每次循环,divider减一,result=result+100/divider 9      * 如果:捕获异常,打印输出“异常抛出了”,返回-110      * 否则:返回result11      * @return12      */13     public int test1(){14         int divider=10;15         int result=100;16         try{17             while(divider>-1){18                 divider--;19                 result=result+100/divider;20             }21             return result;22         }catch(Exception e){23             e.printStackTrace();24             System.out.println("异常抛出了!!");25             return -1;26         }27     }28     public static void main(String[] args) {29         // TODO Auto-generated method stub30         TryCatchTest t1=new TryCatchTest();31         System.out.println("test1方法执行完毕!result的值为:"+t1.test1());32     }33     34 }

运行结果:

结果分析:结果中的红色字抛出的异常信息是由e.printStackTrace()来输出的,它说明了这里我们抛出的异常类型是算数异常,后面还跟着原因:by zero(由0造成的算数异常),下面两行at表明了造成此异常的代码具体位置。

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

在上面例子中再加上一个test2()方法来测试finally语句的执行状况:

 1     /** 2      * divider:除数 3      * result:结果 4      * try-catch捕获while循环 5      * 每次循环,divider减一,result=result+100/divider 6      * 如果:捕获异常,打印输出“异常抛出了”,返回result=999 7      * 否则:返回result 8      * finally:打印输出“这是finally,哈哈哈!!”同时打印输出result 9      * @return10      */11     public int test2(){12         int divider=10;13         int result=100;14         try{15             while(divider>-1){16                 divider--;17                 result=result+100/divider;18             }19             return result;20         }catch(Exception e){21             e.printStackTrace();22             System.out.println("异常抛出了!!");23             return result=999;24         }finally{25             System.out.println("这是finally,哈哈哈!!");26             System.out.println("result的值为:"+result);27         }28         29     }30     31     32     33     public static void main(String[] args) {34         // TODO Auto-generated method stub35         TryCatchTest t1=new TryCatchTest();36         //System.out.println("test1方法执行完毕!result的值为:"+t1.test1());37         t1.test2();38         System.out.println("test2方法执行完毕!");39     }

运行结果:

结果分析:我们可以从结果看出,finally语句块是在try块和catch块语句执行之后最后执行的。finally是在return后面的表达式运算后执行的(此时并没有返回运算后的值,而是先把要返回的值保存起来,管finally中的代码怎么样,返回的值都不会改变,仍然是之前保存的值),所以函数返回值是在finally执行前确定的;

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

这里有个有趣的问题,如果把上述中的test2方法中的finally语句块中加上return,编译器就会提示警告:finally block does not complete normally 

  public int test2(){ 
          int divider=10; 
          int result=100; 
          try{ 
              while(divider>-1){ 
                  divider--; 
                  result=result+100/divider; 
              } 
              return result;10         }catch(Exception e){
              e.printStackTrace();
              System.out.println("异常抛出了!!");
              return result=999;14         }finally{
              System.out.println("这是finally,哈哈哈!!");
              System.out.println("result的值为:"+result);
              return result;//编译器警告18         }
          
      }

分析问题: finally块中的return语句可能会覆盖try块、catch块中的return语句;如果finally块中包含了return语句,即使前面的catch块重新抛出了异常,则调用该方法的语句也不会获得catch块重新抛出的异常,而是会得到finally块的返回值,并且不会捕获异常。

解决问题:面对上述情况,其实更合理的做法是,既不在try block内部中使用return语句,也不在finally内部使用 return语句,而应该在 finally 语句之后使用return来表示函数的结束和返回。如:

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

 总结:

  1、不管有木有出现异常或者try和catch中有返回值return,finally块中代码都会执行;

  2、finally中最好不要包含return,否则程序会提前退出,返回会覆盖try或catch中保存的返回值。

  3.  e.printStackTrace()可以输出异常信息。

  4.  return值为-1为抛出异常的习惯写法。

  5.  如果方法中try,catch,finally中没有返回语句,则会调用这三个语句块之外的return结果。

  6.  finally 在try中的return之后 在返回主调函数之前执行


三、throw和throws关键字

java中的异常抛出通常使用throw和throws关键字来实现。

throw ----将产生的异常抛出,是抛出异常的一个动作

一般会用于程序出现某种逻辑时程序员主动抛出某种特定类型的异常。如:
  语法:throw (异常对象),如:

1 public static void main(String[] args) { 
2     String s = "abc"; 
3     if(s.equals("abc")) { 
4       throw new NumberFormatException(); 
5     } else { 
6       System.out.println(s); 
7     } 
8     //function(); 9 }

运行结果:

Exception in thread "main" java.lang.NumberFormatException
at test.ExceptionTest.main(ExceptionTest.java:67)

throws----声明将要抛出何种类型的异常(声明)。

语法格式:

1 public void 方法名(参数列表)2    throws 异常列表{3 //调用会抛出异常的方法或者:4 throw new Exception();5 }

当某个方法可能会抛出某种异常时用于throws 声明可能抛出的异常,然后交给上层调用它的方法程序处理。如:

 1 public static void function() throws NumberFormatException{ 
 2     String s = "abc"; 
 3     System.out.println(Double.parseDouble(s)); 
 4   } 
 5      6   public static void main(String[] args) { 
 7     try { 
 8       function(); 
 9     } catch (NumberFormatException e) { 
10       System.err.println("非数据类型不能转换。"); 
11       //e.printStackTrace(); 12     } 
13 }

throw与throws的比较
1、throws出现在方法函数头;而throw出现在函数体。
2、throws表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某种异常对象。
3、两者都是消极处理异常的方式(这里的消极并不是说这种方式不好),只是抛出或者可能抛出异常,但是不会由函数去处理异常,真正的处理异常由函数的上层调用处理。

来看个例子:

throws e1,e2,e3只是告诉程序这个方法可能会抛出这些异常,方法的调用者可能要处理这些异常,而这些异常e1,e2,e3可能是该函数体产生的。
throw则是明确了这个地方要抛出这个异常。如:

 1 void doA(int a) throws (Exception1,Exception2,Exception3){ 2       try{ 3          ...... 4   5       }catch(Exception1 e){ 6        throw e; 7       }catch(Exception2 e){ 8        System.out.println("出错了!"); 9       }10       if(a!=b)11        throw new Exception3("自定义异常");12 }

Analysis:
1. Three exceptions may occur in the code block, (Exception1,Exception2,Exception3).
2. If an Exception1 exception occurs, it will be thrown after being caught and handled by the caller of the method.
3. If an Exception2 exception occurs, the method handles it by itself (i.e. System.out.println("An error occurred!");). So this method will no longer throw Exception2 exception, void There is no need to write Exception2 in doA() throws Exception1,Exception3. Because it has been captured and processed using the try-catch statement.
4.Exception3 exception is a certain logic error in this method. The programmer has done the processing himself. If the exception Exception3 is thrown in the case of this logic error, then the method is called The operator should also handle this exception. A custom exception is used here, which will be explained below.

>>>>>>>>>>>>>>>>>>>>> ;>>>>>>>>>>>>>>>>>>>>>>>>> ;>>

Use the throw and throws keywordsYou need to pay attention to the following points:

1. The exception list of throws can throw an exception , or multiple exceptions can be thrown. Each type of exception is separated by a comma

2. Call the method that will throw an exception in the method body or throw an exception first: use throw new Exception () throw is written in the method body, indicating the action of "throwing an exception".

3. If a method calls a method that throws an exception, you must add a try catch statement to try to catch this exception, or add a statement to throw the exception to the higher-level caller. Processing >>>>>>>>>>>>>>>>>>>>>>>>> >>>

Custom exception


##Why use custom Exception, what are the
benefits

?

1. When we are working, the project is developed in modules or functions. Basically, you will not develop an entire project by yourself. Just use a custom exception class Unified the way of displaying external exceptions.

2. Sometimes when we encounter certain verification or problems,

need to end the current request directly. At this time, we can end it by throwing a custom exception. If you If a newer version of SpringMVC is used in the project, there is a controller enhancement. You can write a controller enhancement class through the @ControllerAdvice annotation to intercept custom exceptions and respond to the front end with corresponding information

.

3. Custom exceptions can be thrown when certain special business logic occurs in our project, such as "neutral".equals(sex), We have to throw an exception when the gender is equal to neutral, but Java does not have this exception. Some errors in the system comply with Java syntax, but do not comply with the business logic of our project.

4. Use custom exceptions to inherit related exceptions to throw processed exception information

You can hide the underlying exception, which is safer and the exception information is more intuitive. Custom exceptions can throw the information we want to throw. We can use the thrown information to distinguish the location where the exception occurs. Based on the exception name, we can know where the exception is and modify the program based on the exception prompt information. For example, in the case of NullPointException, we can throw the message "xxx is null" to locate the exception location without outputting stack information.

After talking about why you should use custom exceptions and what are the benefits, let’s take a look at the problems

of custom exceptions:

Needless to say, we cannot expect the JVM (Java Virtual Machine) to automatically throw a custom exception, nor can we expect the JVM to automatically handle a custom exception. The work of detecting exceptions, throwing exceptions, and handling exceptions must be completed by programmers themselves using the exception handling mechanism in the code. This will correspondingly increase some development costs and workload, so if the project does not need it, it does not necessarily have to use custom exceptions. You must be able to weigh it yourself.

Finally, let’s see how to

use

custom exceptions:

In Java you can customize exceptions . There are a few things to keep in mind when writing your own exception classes.

All exceptions must be subclasses of Throwable.

  • 如果希望写一个检查性异常类,则需要继承 Exception 类。

  • 如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。

  • 可以像下面这样定义自己的异常类:

    class MyException extends Exception{ }

     

    我们来看一个实例:

     1 package com.hysum.test; 2  3 public class MyException extends Exception { 4      /** 5      * 错误编码 6      */ 7     private String errorCode; 8  9    10     public MyException(){}11     12     /**13      * 构造一个基本异常.14      *15      * @param message16      *        信息描述17      */18     public MyException(String message)19     {20         super(message);21     }22 23    24 25     public String getErrorCode() {26         return errorCode;27     }28 29     public void setErrorCode(String errorCode) {30         this.errorCode = errorCode;31     }32 33     34 }

    使用自定义异常抛出异常信息:

     1 package com.hysum.test; 2  3 public class Main { 4  5     public static void main(String[] args) { 6         // TODO Auto-generated method stub 7         String[] sexs = {"男性","女性","中性"}; 8                   for(int i = 0; i < sexs.length; i++){ 9                       if("中性".equals(sexs[i])){10                           try {11                             throw new MyException("不存在中性的人!");12                         } catch (MyException e) {13                             // TODO Auto-generated catch block14                             e.printStackTrace();15                         }16                      }else{17                          System.out.println(sexs[i]);18                      }19                 } 
    20     }21 22 }

    运行结果:

    就是这么简单,可以根据实际业务需求去抛出相应的自定义异常。


    四、java中的异常链

    异常需要封装,但是仅仅封装还是不够的,还需要传递异常

    异常链是一种面向对象编程技术,指将捕获的异常包装进一个新的异常中并重新抛出的异常处理方式。原异常被保存为新异常的一个属性(比如cause)。这样做的意义是一个方法应该抛出定义在相同的抽象层次上的异常,但不会丢弃更低层次的信息

    我可以这样理解异常链:

    把捕获的异常包装成新的异常,在新异常里添加原始的异常,并将新异常抛出,它们就像是链式反应一样,一个导致(cause)另一个。这样在最后的顶层抛出的异常信息就包括了最底层的异常信息。

    》场景

    比如我们的JEE项目一般都又三层:持久层、逻辑层、展现层,持久层负责与数据库交互,逻辑层负责业务逻辑的实现,展现层负责UI数据的处理。

    有这样一个模块:用户第一次访问的时候,需要持久层从user.xml中读取数据,如果该文件不存在则提示用户创建之,那问题就来了:如果我们直接把持久层的异常FileNotFoundException抛弃掉,逻辑层根本无从得知发生任何事情,也就不能为展现层提供一个友好的处理结果,最终倒霉的就是展现层:没有办法提供异常信息,只能告诉用户“出错了,我也不知道出了什么错了”—毫无友好性而言。

    正确的做法是先封装,然后传递,过程如下:

     1.把FileNotFoundException封装为MyException。

    2.抛出到逻辑层,逻辑层根据异常代码(或者自定义的异常类型)确定后续处理逻辑,然后抛出到展现层。

    3.展现层自行确定展现什么,如果管理员则可以展现低层级的异常,如果是普通用户则展示封装后的异常。

    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    》示例

     1 package com.hysum.test; 2  3 public class Main { 4     public void test1() throws RuntimeException{ 5         String[] sexs = {"男性","女性","中性"}; 6         for(int i = 0; i < sexs.length; i++){ 7             if("中性".equals(sexs[i])){ 8                 try { 9                     throw new MyException("不存在中性的人!");10                 } catch (MyException e) {11                     // TODO Auto-generated catch block12                     e.printStackTrace();13                     RuntimeException rte=new RuntimeException(e);//包装成RuntimeException异常14                     //rte.initCause(e);15                     throw rte;//抛出包装后的新的异常16                 }17            }else{18                System.out.println(sexs[i]);19            }20       } 
    21     }22     public static void main(String[] args) {23         // TODO Auto-generated method stub24         Main m =new Main();25         26         try{27         m.test1();28         }catch (Exception e){29             e.printStackTrace();30             e.getCause();//获得原始异常31         }32         33     }34 35 }

    Running results:

    Result analysis: We can see that the console first outputs the original exception, which is output by e.getCause(); and then outputs e.printStackTrace(), here you can see Caused by: The original exception is consistent with the output of e.getCause(). This forms an abnormal chain. The function of initCause() is to wrap the original exception. When you want to know what exception occurred at the bottom layer, you can get the original exception by calling getCause().

    >>>>>>>>>>>>>>>>>>>>> ;>>>>>>>>>>>>>>>>>>>>>>>>> ;>>

    》Recommendation

    Exceptions need to be encapsulated and passed. When we develop the system, we should not "swallow" exceptions or throw them "nakedly" Exceptions can be thrown after being encapsulated or passed through an exception chain to make the system more robust and friendly.


    5. Conclusion

    The knowledge of exception handling in Java is complicated and a bit difficult to understand. I have summarized the following points for you when using Java exception handling:

    Good coding habits:

    1. When handling runtime exceptions, use logic to reasonably avoid and assist try-catch processing

    2. After multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed

    3. For uncertain code, you can also add try-catch to handle Potential exceptions

    4. Try to handle exceptions as much as possible. Remember to simply call printStackTrace() to print

    5. How to handle exceptions specifically depends on different business needs and exception types.

    6. Try to add a finally statement block to release the occupied resources

    The above is the detailed content of Detailed introduction to exceptions in JAVA. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Previous article:The three major features of Java-encapsulation, inheritance, and polymorphismNext article:The three major features of Java-encapsulation, inheritance, and polymorphism

    Related articles

    See more