Home  >  Article  >  Java  >  Why exception handling? Detailed explanation of java exception handling mechanism

Why exception handling? Detailed explanation of java exception handling mechanism

php是最好的语言
php是最好的语言Original
2018-08-10 11:34:267641browse

1. Background introduction

Why should exception handling be performed?

For computer programs, no one can guarantee that it will not make errors when running. The main sources of errors are as follows:

  • Code Error

  • Illegal user input

  • Device errors and physical limitations: disk full, memory overflow, hardware problems, network interruption...

There is an error in the program, so how to solve it? In the Java language, it provides an exception handling mechanism to help us deal with this problem.

The exception mechanism can separate the exception handling code in the program from the normal business code, ensuring that the program code is more elegant and can improve the robustness of the program.

                        Java’s exception mechanism mainly relies on the five keywords try, catch, finally, throw and throws.

                                                                                                         are followed by a code block enclosed in curly braces (the curly braces cannot be omitted), referred to as try block, which contains code that may cause exceptions; after catch, the corresponding exception type and a code block, Used to indicate that the catch block is used to process this type of code block; multiple catch blocks can also be followed by a finally block. The finally block is used to recycle the physical resources opened in the try block. The exception mechanism will ensure that the finally block is always Execution; the throws keyword is mainly used in method signatures to declare exceptions that may be thrown by the method; throw is used to throw an actual exception, and throw can be used as a separate statement to throw a specific exception object.

A simple example is as follows

try {
   // args表示传入的形参,args[0]表示传入的第一个形参,args[1]表示传入的第二个形参
   int a = Integer.parseInt(args[0]);
   int b = Integer.parseInt(args[1]);
   int c = a / b;
   System.out.println("您输入的两个数相除的结果是:"+c);
} catch (IndexOutOfBoundsException ie){
   System.out.println("数组越界:运行程序时输入的参数个数不够");
} catch (NumberFormatException ne){
   System.out.println("数字格式异常:程序只能接收整数参数");
} catch (ArithmeticException ae){
   // 除0异常
   System.out.println("算术异常");
} catch (Exception e){
   System.out.println("未知异常");
}

2. Knowledge analysis

2.1 Exception handling mechanism

2.1.1 Use try... catch capture exception

try{

//Business implementation code

} catch (Exception e){

//Exception handling code

}

Execution process (or logic):

If the code in the try block can run smoothly, then "everything is normal"; if an error occurs when executing the business logic code in the try block Exception, the system will automatically generate an exception object, which is submitted to the Java runtime environment. This process is called throwing an exception. When the Java runtime environment receives an exception object, it will look for a catch block that can handle the exception object. If a suitable catch block is found, the exception object will be handed over to the catch block for processing. This process is called catching. Exception; if the Java runtime environment cannot find the catch block that catches the exception, the runtime environment terminates and the Java program will also exit.

Note: Regardless of whether the program code block is in a try block, or even the code in the catch block, as long as an exception occurs when executing the code block, the system will always automatically generate an exception object. If the program does not define any catch block for this code, the Java runtime environment cannot find the catch block to handle the exception, and the program exits.

2.1.2 Inheritance system of exception classes

When the Java runtime environment receives an exception object, it will determine whether the exception object is an instance of the exception class or its subclass after the catch block. , if so, the Java runtime environment will call the catch block to handle the exception, otherwise compare the exception object again with the exception class in the next catch block.

Java exception capture process

Why exception handling? Detailed explanation of java exception handling mechanism

## As can be seen from the figure, there can be multiple catch blocks after the try block, which is to target different exception classes. Provide different exception handling methods. When different unexpected situations occur in the system, the system will generate different exception objects, and the Java runtime will decide which catch block to use to handle the exception based on the exception class to which the exception object belongs.

Under normal circumstances, if the try block is executed once, only one catch block will be executed after the try block, and it is never possible to have multiple catch blocks executed. Unless continue is used in the loop to start the next loop, and the try block is re-run in the next loop, this may cause multiple catch blocks to be executed.

Inheritance relationship between common exception classes in Java

Why exception handling? Detailed explanation of java exception handling mechanism

Java把所有的非正常情况分为两种:异常和错误,它们都继承Throwable父类。

        Error错误,一般指与虚拟机相关的问题,如系统崩溃、虚拟机错误、动态链接失败、资源耗尽  等,这种错误无法恢复或不可能捕获,将导致应用程序中断。通常应用程序无法处理这些错误,因此应用程序不应该试图使用catch块来捕获Error对象,也无须声明可能抛出Error及其任何子类对象。

常见异常:

IndexOutOfBoundsException:数组越界异常,原因在于运行程序时输入的参数个数不够

NumberFormatException:数字格式异常,原因在于运行程序时输入的参数不是数字,而是字母

ArithmeticException:除0异常

Exception:当发生未知异常时,该异常对象总是Exception类或其子类的实例,可用Exception对应的catch块处理该异常

NullPointerException:空指针异常,当试图调用一个null对象的实例或者实例变量时,会引发此异常

注:进行异常捕获时不仅应该把Exception类对应的catch块放在最后,而且所有父类异常的catch块都应该排在子类异常catch块的后面,即先捕获小异常,再捕获大异常,否则将出现编译错误。(若父类在前,则排在它后面的子类的catch块将永远不会获得执行的机会,因为检索catch块是从上到下依次执行的)

2.1.3 Java7提供多异常捕获

在Java7之前,每个catch块只能捕获一种类型的异常,但从Java7开始,一个catch块可以捕获多种类型的异常。

使用一个catch块捕获多种类型的异常时需要注意如下两个地方:

  • 捕获多种类型的异常时,多种异常类型之间用 | 隔开。

  • 捕获多种类型的异常时,异常变量有隐式的final修饰,因此程序不能对异常变量重新赋值。

try {
         int a = Integer.parseInt(args[0]);
         int b = Integer.parseInt(args[1]);
         int c = a / b;
         System.out.println("您输入的两个数相除的结果是:"+c);
      } catch (IndexOutOfBoundsException|NumberFormatException|ArithmeticException e){
         System.out.println("程序发生了数组越界、数字格式异常、算术异常之一");
         
         // 捕获多异常时,异常变量默认有final修饰
         // 所以下面代码编译报错
//        e = new ArithmeticException("text");
      } catch (Exception e){
         System.out.println("未知错误");
         
         // 捕获一种类型的异常时,异常变量没有final修饰
         // 所有下面代码完全正确
         e = new RuntimeException("test");
      }

2.1.4 访问异常信息

         如果程序需要在catch块中访问异常对象的相关信息,则可以通过访问catch后面括号中的异常形参来获得。当Java运行时决定调用某个catch块来处理该异常对象时,会将异常对象赋给catch块后的异常参数,程序即可通过该参数来获得异常的相关信息。

所有的异常对象都包含了如下几个常用方法:

  • getMessage():返回该异常的详细描述字符串。

  • printStackTrace():将该异常的跟踪栈信息输出到标准错误流。

  • printStackTrace(PrintStream s):将该异常的跟踪栈信息输出到指定输出流。

  • getStackTrace():返回该异常的跟踪栈信息。

2.1.5 使用finally

 有时,程序在try块里打开了一些物理资源(例如数据库连接、网络连接和磁盘文件等),这些物理资源都必须显示回收。

注:Java的垃圾回收机制不会回收任何物理资源,垃圾回收机制只能回收堆内存中对象所占用的内存。

         为了保证一定能回收try块中打开的物理资源,异常处理机制提供了finally块。不管try块中的代码是否出现异常,也不管哪一个catch块是否被执行,甚至在try块或者catch块中执行了return语句,finally块总会被执行。

完整的Java异常处理语法结构:

try{

// 业务实现代码

} catch (Exception1 e){

// 异常处理块1

} catch (Exception2 e){

// 异常处理块2

} finally {

// 资源回收块

}      

        Only the try block is required in the exception handling syntax structure. If there is no try block, there cannot be the following catch block and finally block; the catch block and finally block are both optional, but the catch block and finally block must at least appear One of them can also appear at the same time; there can be multiple catch blocks, and the catch block that catches the parent class exception must be located behind the catch subclass exception; but there cannot be only try blocks, no catch blocks, and no finally blocks; multiple catches block must come after try block and finally block must come after all catch blocks.

Note: Unless the method to exit the virtual machine is called in the try block or catch block, no matter what code is executed in the try block or catch block or what situation occurs, the finally block of exception handling will always be executed.

Under normal circumstances, try to avoid using statements such as return or throw in the finally block that cause the method to terminate, otherwise some very strange situations may occur.

2.1.6 Nesting of exception handling

The situation where the complete exception handling process is included in the try block, catch block or finally block is called the nesting of exception handling.

The exception handling process code can be placed anywhere where executable code can be placed. Therefore, the complete exception handling process can be placed in a try block, a catch block, or finally block.

The depth of the nested nested is not significant, but it is usually not necessary to use more than two layers of nested abnormal treatment. The level is too deep, which is not necessary, but causes the program to read.

2.1.7 Java7’s try statement that automatically closes resources

Java7 has enhanced the function of the try statement. It allows a pair of parentheses to be followed by the try keyword. The parentheses can be declared, Initialize one or more resources. The resources here refer to those resources that must be explicitly closed at the end of the program (such as database connections, network connections, etc.). The try statement automatically closes these resources at the end of the statement.

Note: In order to ensure that the try statement can close the resource normally, these resource implementation classes must implement the AutoCloseable or Closeable interface. To implement these two interfaces, the close() method must be implemented. (Closeable is a sub-interface of AutoCloseable; the close() method in the Closeable interface declares that it throws IOException, so its implementation class can only declare that it throws IOException or its subclass when implementing the close() method; the close in the AutoCloseable interface () method declaration throws Exception, so its implementation class can declare to throw any exception when implementing the close() method)

The try statement that automatically closes the resource is equivalent to containing an implicit finally block ( This finally block is used to close resources), so this try statement can have neither a catch block nor a finally block. If the program needs it, multiple catch blocks and a finally block can be included after the try statement that automatically closes the resource.

Java7 to rewrite all the "resource classes" (including the various types of the file IO, the JDBC programming connection, statement and other interfaces). .

2.2 Checked exception and Runtime exception system

Java exceptions are divided into two categories: Checked exceptions and Runtime exceptions (runtime exceptions, some are also called unchecked exceptions). All instances of the RuntimeException class and its subclasses are called Runtime exceptions; exception instances that are not RuntimeException classes and their subclasses are called Checked exceptions. (To identify the type of exception when using it, just look at the declared exception class to know)

Only the Java language provides Checked exceptions, and no other languages ​​provide Checked exceptions. Java believes that Checked exceptions are exceptions that can be handled (repaired), so the Java program must explicitly handle Checked exceptions. If the program does not handle Checked exceptions, an error will occur during compilation of the program and it will fail to compile.

There are two ways to handle Checked exceptions:

  • The current method clearly knows how to handle the exception, and the program should use the try...catch block to capture the exception. Exception, and then fix the exception in the corresponding catch block.

  • The current method does not know how to handle this exception. It should be declared to throw this exception when defining the method.

Runtime exceptions are more flexible. Runtime exceptions do not need to be explicitly declared to be thrown. If the program needs to catch Runtime exceptions, it can also be implemented using try...catch blocks.

Note: Java core technology

        在Exception层次结构中,有两个分支:一个分支派生于RuntimeException;另一个分支包含其他异常。划分这两个分支的规则是:由程序错误导致的异常属于RuntimeException;而程序本身没有问题,但由于像I/O错误这类问题导致的异常属于其他异常。

          Java语言规范将派生于Error类或RuntimeException类的所有异常称为未(不受?)检查异常(unchecked),所有其他的异常称为已检查异常(checked)。(在编译期间进行检查,编译器将检查是否为所有的已检查异常提供了异常处理器)  ??????????? 有待讨论

2.3 使用throws抛出异常

       使用throws声明抛出异常的思路是,当前方法不知道如何处理这种类型的异常,该异常应该由上一级调用者处理;如果main方法也不知道如何处理这种类型的异常,也可以使用throws声明抛出异常,该异常将交给JVM处理。JVM对异常的处理方法是,打印异常的跟踪栈信息,并中止程序运行,这就是平时我们的程序在遇到异常后自动结束的原因。

         throws声明抛出只能在方法签名中使用,throws可以声明多个异常类,多个异常类之间使用逗号隔开。

         一旦使用throws语句声明抛出异常,那么就无需使用try...catch块来捕获该异常了。

        使用throws声明抛出异常时有一个限制,就是方法重写时“两下”中的一条规则:子类方法声明抛出的异常类型应该是父类方法声明抛出的异常类型的子类或相同,子类方法声明抛出的异常不允许比父类方法声明抛出的异常多。(即设置了上限)

使用Checked异常至少存在如下两大不便之处:

  • 对于程序中的Checked异常,Java要求必须显示捕获并处理该异常,或者显示声明抛出该异常,这增加了编程复杂度。

  • 如果在方法中显示声明抛出Checked异常,将会导致方法签名与异常耦合,如果该方法是重写父类的方法,则该方法抛出的异常还会受到被重写方法所抛出异常的限制。

         在大部分时候推荐使用Runtime异常,而不使用Checked异常,尤其当程序需要自行抛出异常时,使用Runtime异常将更加简洁。

         当使用Runtime异常时,程序无需在方法中声明抛出Checked异常,一旦发生了自定义错误,程序只管抛出Runtime异常即可。对于Runtime异常,Java编译器不要求必须进行异常捕获处理或者抛出声明,由程序员自行决定。

         使用Runtime异常省事,但Checked异常也有其优势,Checked异常能在编译时提醒程序员代码可能存在的问题,提醒程序员必须注意处理该异常,或者声明该异常有方法的调用者来处理,从而避免程序员因为粗心而忘记处理该异常的错误。

2.4 使用throw抛出异常

       当程序出现错误时,系统会自动抛出异常,除此之外,Java也允许程序自行抛出异常,自行抛出异常使用throw语句来完成。

2.5 自定义异常类

       用户自定义异常都应该继承Exception基类,如果希望自定义Runtime异常,则应该继承RuntimeException基类。定义异常类时通常需要提供两个构造器:一个是无参数的构造器;另一个是带一个字符串参数的构造器,这个字符串将作为该异常对象的描述信息(即异常对象的getMessage()方法的返回值)。

package AuctionException;

// 自定义异常都要继承Exception基类,如果希望自定义Runtime异常,则应该继承RuntimeException基类。
// 自定义异常类需要提供两个构造器:一个是无参数的构造器;另一个是带一个字符串参数的构造器,这个字符串作为
// 该异常对象的描述信息(即异常对象的getMessage()方法的返回值)
public class AuctionException extends Exception{
   
   //1、无参数的构造器
   public AuctionException(){
   }
   //2、带一个字符串参数的构造器
   public AuctionException(String msg){
      // 通过super调用父类的构造器
      super(msg);
   }
}

2.6 catch和throw同时使用

       在实际应用中,当一个异常出现时,单靠某个方法无法完全处理该异常,必须由几个方法协作才可以完全处理该异常。也就是说,在异常出现的当前方法中,程序只对异常进行部分处理,还有些处理需要在该方法的调用者中才能完成,所以应该再次抛出异常,让该方法的调用者也能捕获到异常。

         为了实现这种通过多个方法协作处理同一个异常的情形,可以在catch块中结合throw语句来完成。

         这种catch和throw结合使用使用的情况在大型企业级应用中非常常用,企业级应用对异常的处理通常分成两个部分:一是后台需要通过日志来记录异常发生的详细情况;二是应用还需要根据异常向应用使用者传达某种提示。

package CatchAndThrow;

import AuctionException.AuctionException;

public class CatchAndThrow {
   
   private double initPrice = 30.0;
   
   // 因为该方法中显示抛出了AuctionException异常
   // 所以此处需要声明抛出AuctionException异常
   public void bid(String bidPrice) throws AuctionException{
      double d = 0.0;
      try {
         d = Double.parseDouble(bidPrice);
      } catch (Exception e){
         
         // 此处完成本方法中可以对异常执行的修复处理
         // 此处仅仅是控制台打印异常的跟踪栈信息
         e.printStackTrace();
         
         // 再次抛出自定义异常
         throw new AuctionException("竞拍价必须是数值,不能包含其他字符");
      }
      
      if (initPrice > d){
         throw new AuctionException("竞拍价比起拍价低,不允许竞拍");
      }
      
      initPrice = d;
   }
   
   public static void main(String[] args){
      
      CatchAndThrow catchAndThrow = new CatchAndThrow();
      try{
         catchAndThrow.bid("df");
      } catch (AuctionException ae){
         // 再次捕获到bid()方法中的异常,并对该异常进行处理,此处是将异常的详细描述信息输出到标准错误(err)输出
         System.err.println(ae.getMessage());
      }
   }
}

2.7 异常跟踪栈

       异常对象的printStackTrace()方法用于打印异常的跟踪栈信息,根据printStackTrace()方法的输出结果,开发者可以找到异常的源头,并跟踪到异常一路触发的过程。

3、常见问题

3.1 为什么在finally块中不能访问try块中声明的变量?

答:try块里声明的变量是代码块内局部变量,它只在try块内有效,在catch块及finally块中不能访问该变量。

3.2 为什么最好不要使用catch all语句?

答:所谓catch all语句指的是一种异常捕获模块,它可以处理程序发生的所有可能异常。例如使用Exception或者Throwable类捕获所有异常,虽然这种方式能够处理异常,但是它不能精确描述引发异常的原因,我们很难进行准确的排查。

3.3 有没有关于注解方式的异常处理?

答:有的,比如spring有基于注解的全局异常处理方式(使用@ExceptionHandler)

4、参考文献

摘自《疯狂Java讲义 》第三版,文中代码模仿书中例子所敲。

今天的分享就到这了,希望大家多多指正,互相学习~

相关推荐:

java异常(Exception)处理机制示例代码分享

简单介绍Java的异常和架构

The above is the detailed content of Why exception handling? Detailed explanation of java exception handling mechanism. 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