About I/O exceptions

2016.08.09

 

Class Content: Exception Handling

 

1. JAVA exception

There are 5 common exceptions, namely: try, catch, finally, throw, throws 

The flow of the program is:

Run into the try block. If an exception is thrown, go to the catch. When the catch is processed, execute the code of the finally block, and then execute the code after the finally block. If no exception is thrown, execute the try block, also execute the code of finally, and then execute the statement after finally.

Throw is a statement that throws an exception, throws is a method that throws an exception, throws can be used alone, and throw cannot be used alone.

Java exception class structure hierarchy:

  In Java, all exceptions have a common ancestor Throwable (throwable). Throwable specifies the commonality of any problem in the code that can be transported through a Java application by the exception propagation mechanism.

 Throwable:  There are two important subclasses: Exception (exception) and Error (error), both of which are important subclasses of Java exception handling, each containing a large number of subclasses.

 Error (error): It is an error that the program cannot handle, indicating a more serious problem in running the application. Most errors have nothing to do with what the author of the code did, but rather represent a problem with the JVM (Java Virtual Machine) when the code is running. For example, a Java virtual machine runs an error (Virtual MachineError), when the JVM no longer has the memory resources needed to continue the operation, an OutOfMemoryError will occur. When these exceptions occur, the Java Virtual Machine (JVM) typically chooses to terminate the thread.

These errors indicate that the failure occurs in the virtual machine itself, or when the virtual machine tries to execute an application, such as a Java virtual machine runtime error (Virtual MachineError), a class definition error (NoClassDefFoundError), and so on. These errors are untraceable because they are outside the control and processing power of the application, and most are not allowed to occur while the program is running. In a well-designed application, even if an error does occur, there should be no inherent attempt to handle the abnormal condition it causes. In Java, errors are described by subclasses of Error.

 Exception: An exception that the program itself can handle.

       The Exception class has an important subclass, RuntimeException. The RuntimeException class and its subclasses represent errors thrown by "common JVM operations". For example, an attempt to use a null-valued object reference, division by zero, or array out-of-bounds throws a runtime exception (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException, respectively.

   Note: The difference between exceptions and errors: exceptions can be handled by the program itself, while errors cannot be handled.

 Generally, Java exceptions (including Exception and Error) are divided into checked exceptions and unchecked exceptions .

      Checkable exceptions (exceptions that the compiler requires to be handled): Exceptions that are easy to occur and tolerable when the correct program is running. Although the checkable exception is an abnormal situation, its occurrence can be predicted to a certain extent, and once such an abnormal situation occurs, it must be handled in a certain way.

      Except for RuntimeException and its subclasses, other Exception classes and their subclasses are all checkable exceptions. The characteristic of this kind of exception is that the Java compiler will check it, that is, when such an exception may occur in the program, either catch it with a try-catch statement, or declare it with a throws clause, otherwise the compilation will not pass. .

     Unchecked exceptions (exceptions that the compiler does not require mandatory disposal): including runtime exceptions (RuntimeException and its subclasses) and errors (Error).

     Exception This kind of exception is divided into two categories: run-time exception and non-run-time exception (compiled exception). Programs should try to handle these exceptions as much as possible.

 Runtime exceptions: All are RuntimeException class and its subclass exceptions, such as NullPointerException (null pointer exception), IndexOutOfBoundsException (subscript out of bounds exception), etc. These exceptions are unchecked exceptions, and the program can choose to capture and handle them or not. These exceptions are generally caused by program logic errors, and the program should avoid the occurrence of such exceptions as much as possible from a logical point of view.

      The characteristic of runtime exception is that the Java compiler does not check it, that is, when such an exception may occur in the program, even if it is not caught with a try-catch statement or thrown with a throws clause statement, it will also be thrown. Compiled.
       Non-runtime exceptions (compiled exceptions): exceptions other than RuntimeException, all of which belong to the Exception class and its subclasses. From the perspective of program syntax, it is an exception that must be handled. If it is not handled, the program cannot be compiled. Such as IOException, SQLException, etc., as well as user-defined Exception exceptions, generally do not customize checked exceptions.

 2. Handling exception mechanism

 In Java applications, the exception handling mechanism is: throw exceptions, catch exceptions.

        抛出异常:当一个方法出现错误引发异常时,方法创建异常对象并交付运行时系统,异常对象中包含了异常类型和异常出现时的程序状态等异常信息。运行时系统负责寻找处置异常的代码并执行。

        捕获异常:在方法抛出异常之后,运行时系统将转为寻找合适的异常处理器(exception handler)。潜在的异常处理器是异常发生时依次存留在调用栈中的方法的集合。当异常处理器所能处理的异常类型与方法抛出的异常类型相符时,即为合适 的异常处理器。运行时系统从发生异常的方法开始,依次回查调用栈中的方法,直至找到含有合适异常处理器的方法并执行。当运行时系统遍历调用栈而未找到合适 的异常处理器,则运行时系统终止。同时,意味着Java程序的终止。

        对于运行时异常、错误或可查异常,Java技术所要求的异常处理方式有所不同。

        由于运行时异常的不可查性,为了更合理、更容易地实现应用程序,Java规定,运行时异常将由Java运行时系统自动抛出,允许应用程序忽略运行时异常。

       对于方法运行中可能出现的Error,当运行方法不欲捕捉时,Java允许该方法不做任何抛出声明。因为,大多数Error异常属于永远不能被允许发生的状况,也属于合理的应用程序不该捕捉的异常。

       对于所有的可查异常,Java规定:一个方法必须捕捉,或者声明抛出方法之外。也就是说,当一个方法选择不捕捉可查异常时,它必须声明将抛出异常。

        能够捕捉异常的方法,需要提供相符类型的异常处理器。所捕捉的异常,可能是由于自身语句所引发并抛出的异常,也可能是由某个调用的方法或者Java运行时 系统等抛出的异常。也就是说,一个方法所能捕捉的异常,一定是Java代码在某处所抛出的异常。简单地说,异常总是先被抛出,后被捕捉的。

         任何Java代码都可以抛出异常,如:自己编写的代码、来自Java开发环境包中代码,或者Java运行时系统。无论是谁,都可以通过Java的throw语句抛出异常。

        从方法中抛出的任何异常都必须使用throws子句。

        捕捉异常通过try-catch语句或者try-catch-finally语句实现。

 

        总体来说,Java规定:对于可查异常必须捕捉、或者声明抛出。允许忽略不可查的RuntimeException和Error。

 

      try 块:用于捕获异常。其后可接零个或多个catch块,如果没有catch块,则必须跟一个finally块。
     catch 块:用于处理try捕获到的异常。
     finally 块:无论是否捕获或处理异常,finally块里的语句都会被执行。当在try块或catch块中遇到return语句时,finally语句块将在方法返回之前被执行。在以下4种特殊情况下,finally块不会被执行:
        1)在finally语句块中发生了异常。
        2)在前面的代码中用了System.exit()退出程序。
        3)程序所在的线程死亡。
        4)关闭CPU

try-catch-finally 规则(异常处理语句的语法规则):

1)  必须在 try 之后添加 catch 或 finally 块。try 块后可同时接 catch 和 finally 块,但至少有一个块。
2) 必须遵循块顺序:若代码同时使用 catch 和 finally 块,则必须将 catch 块放在 try 块之后。
3) catch 块与相应的异常类的类型相关。
4) 一个 try 块可能有多个 catch 块。若如此,则执行第一个匹配块。即Java虚拟机会把实际抛出的异常对象依次和各个catch代码块声明的异常类型匹配,如果异常对象为某个异常类型或其子类的实例,就执行这个catch代码块,不会再执行其他的 catch代码块
5) 可嵌套 try-catch-finally 结构。
6) 在 try-catch-finally 结构中,可重新抛出异常。
7) 除了下列情况,总将执行 finally 做为结束:JVM 过早终止(调用 System.exit(int));在 finally 块中抛出一个未处理的异常;计算机断电、失火、或遭遇病毒攻击。

 

try、catch、finally语句块的执行顺序:

 

1)当try没有捕获到异常时:try语句块中的语句逐一被执行,程序将跳过catch语句块,执行finally语句块和其后的语句;

2)当try捕获到异常,catch语句块里没有处理此异常的情况:当try语句块里的某条语句出现异常时,而没有处理此异常的catch语句块时,此异常将会抛给JVM处理,finally语句块里的语句还是会被执行,但finally语句块后的语句不会被执行;

3)当try捕获到异常,catch语句块里有处理此异常的情况:在try语句块中是按照顺序来执行的,当执行到某一条语句出现异常时,程序将跳到catch语句块,并与catch语句块逐一匹配,找到与之对应的处理程序,其他的catch语句块将不会被执行,而try语句块中,出现异常之后的语句也不会被执行,catch语句块执行完后,执行finally语句块里的语句,最后执行finally语句块后的语句;

 

 Java常见异常

  

在Java中提供了一些异常用来描述经常发生的错误,对于这些异常,有的需要程序员进行捕获处理或声明抛出,有的是由Java虚拟机自动进行捕获处理。Java中常见的异常类:

 

1. runtimeException子类:

    1、 java.lang.ArrayIndexOutOfBoundsException

    数组索引越界异常。当对数组的索引值为负数或大于等于数组大小时抛出。

    2、java.lang.ArithmeticException

    算术条件异常。譬如:整数除零等。

    3、java.lang.NullPointerException

    空指针异常。当应用试图在要求使用对象的地方使用了null时,抛出该异常。譬如:调用null对象的实例方法、访问null对象的属性、计算null对象的长度、使用throw语句抛出null等等

    4、java.lang.ClassNotFoundException

    找不到类异常。当应用试图根据字符串形式的类名构造类,而在遍历CLASSPAH之后找不到对应名称的class文件时,抛出该异常。

   5、java.lang.NegativeArraySizeException  数组长度为负异常

   6、java.lang.ArrayStoreException 数组中包含不兼容的值抛出的异常

   7、java.lang.SecurityException 安全性异常

   8、java.lang.IllegalArgumentException 非法参数异常

2.IOException

IOException:操作输入流和输出流时可能出现的异常。

EOFException   文件已结束异常

FileNotFoundException   文件未找到异常

3. 其他

ClassCastException    类型转换异常类

ArrayStoreException  数组中包含不兼容的值抛出的异常

SQLException   操作数据库异常类

NoSuchFieldException   字段未找到异常

NoSuchMethodException   方法未找到抛出的异常

NumberFormatException    字符串转换为数字抛出的异常

StringIndexOutOfBoundsException 字符串索引超出范围抛出的异常

IllegalAccessException  不允许访问某类异常

InstantiationException  当应用程序试图使用Class类中的newInstance()方法创建一个类的实例,而指定的类对象无法被实例化时,抛出该异常

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327058314&siteId=291194637
Recommended