Java exception mechanism in-depth understanding of

1. Overview of abnormal

1.1 What is an exception?

Abnormal : Program abnormal event due to an external problem caused the program occurs during operation, an exception will interrupt the operation of the program occurs. (In the Java programming language object-oriented) anomaly itself is an object, an exception is to generate an exception object. Note The exception is not an error in java, there are explained in the anomalies of the classification below.
For the life of chestnuts to explain anomalies it, if you usually drive to work is, in general, you can go to work on time to the company, but today special circumstances, is experiencing a highway construction, in which case, if you did not do any treatment, it may lead to work late. This "road construction" is a program exception, he is an external event caused the problem, not your own problem arises. (Aside: But the boss does not care what your problems led to late, you're late anyway ....)

1.2 How to handle exceptions?

1.2.1 The traditional exception handling

If now requires the console, input dividend and divisor, quotient.

Traditional practices like this:

static void main public (String [] args) {
        System.out.println ( "Enter a dividend:");
        Scanner Scanner new new SC = (the System.in);
        IF (sc.hasNextInt ()) {           
            int num1 = SC .nextInt ();
            System.out.println ( "enter a divisor:");
            IF (sc.hasNextInt ()) {               
                int num2 = sc.nextInt ();
                IF (num2 == 0) {
                    the System.out. println ( "divisor is not 0!");
                } the else {
                    int = R & lt num1 / num2;
                    System.out.println ( "R & lt =" + R & lt);
                }
            } the else {
                System.out.println ( "invalid divisor input ! ");
            }
        the else {}
            // possible console input string
            System.out.println ( "dividend input invalid!");
        }

    }

Can be seen from the above example, such a simple business requirements, the code should be written so long, because there are many issues to consider, write code that will feel very tired, but there is an exception, the program will be interrupted, not execution code behind. Therefore, Java programming language provides the ability to use exception handling mechanism for exception handling procedures.

1.2.2 java exception handling

In Java, exception handling process:

This process as you encounter road construction work, you make a deal - walking detour to avoid road construction, so that you arrive on time company!

2. Exceptional classification

In Java, all exceptions have a common ancestor Throwable (throwable). Throwable specify the code available in any common problems anomalous propagation mechanism of transmission through Java applications.

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

Error (error) : wrong program can not handle, indicate more serious problems running the application. Most errors unrelated to the operation and execution of code writers, and that the problem code is running JVM (Java Virtual Machine) appears. For example, Java virtual machine runtime error (Virtual MachineError), when the JVM is no longer required memory resources to continue operations, OutOfMemoryError will appear. When these exceptions occur, Java Virtual Machine (JVM) will generally choose to terminate a thread.

These errors indicate a failure in its own virtual machine, or VM occurs when trying to execute applications such as Java Virtual Machine runtime error (Virtual MachineError), the class definition error (NoClassDefFoundError) and so on. These errors are not checked because they are outside the control and processing power of the application, but the vast majority are not allowed in the program is running situation. For application design and reasonable, even if an error does occur, in essence, we should not try to deal with the abnormal situation caused by it. In Java, the error described by the subclasses of Error.

Exception (abnormal ): abnormal program itself can handle. Exception class has an important subclass of RuntimeException. RuntimeException and its subclasses indicates an error caused by "JVM common operations." For example, when trying to use a null object reference, division by zero or array bounds, respectively, an exception is thrown (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException runtime. Note: the difference between exceptions and errors: the program itself may be an exception handling, error handling is not. Typically, Java exceptions (including Exception and Error) to be investigated into the abnormal (checked exceptions) and can not check the abnormal (unchecked exceptions).

Can be checked exception (the compiler requires an exception must be disposed of) :, reason can accommodate abnormal conditions the correct procedures in the operation, it is easy to arise. Although it is to be investigated abnormal abnormal situation, but to some extent it occurs as can be expected, and once this abnormal situation occurs, we must take some manner for processing.

In addition to its subclasses RuntimeException other Exception class and its subclasses are checked exception belong to . This unusual feature is the Java compiler will check it, that is to say, such an exception may occur when the program or capture it with the try-catch statement, either with a throws clause declared throws it, otherwise the compiler will not pass .

Not check exception (the compiler does not require unusual disposal mandatory): Exception (a RuntimeException its subclasses) and error (Error) comprises a runtime.

Exception This anomaly points abnormal and non-runtime exceptions (compiled abnormal) two categories runtime. Program should be to deal with these exceptions as possible.

Runtime exceptions: all abnormalities RuntimeException class and its subclasses, such as a NullPointerException (null pointer exception), an IndexOutOfBoundsException (subscript bounds exception), these abnormalities are not checked exception, capturing processing program may be selected, or may not handle. These abnormalities are generally caused by the program logic errors, the program should avoid such abnormal logically possible. Runtime exception is characterized by a Java compiler does not check it, that is to say, such an exception may occur when the program even without a try-catch statement catches it, throws clause declared useless throw it, will compile.

Abnormality (abnormality compilation) Non-operating: is Exception belong to the class and its subclasses other than a RuntimeException type. From a linguistic point of view the program is an exception must be handled, if not addressed, the program will not compile. As IOException, SQLException Exception and other user-defined exception, no custom abnormalities in general.

3. exception handling mechanism

On the face of abnormal interpretation should now have some understanding of the anomaly. Now be described in java is how to handle the exception.

  • Java objects used to represent the abnormality.
  • java is to handle exceptions via try-catch, try-catch-finally, try-catch-catch ... statement.

3.1 try-catch

Use 3.1.1 try-catch of

try {} block may be used to perform an abnormality code (type name of the exception object exception) catch {} block is used to capture and handle exceptions.

{the try
    // there may be an exception code segments
    // possible occurrence of an abnormality code segments 2
} the catch (Exception Type E) {
    // exception handling code segment 3
}
// code segment 4

1.2.1 The process of dividing the two problems demo:

static void main public (String [] args) {
        Scanner Scanner new new SC = (the System.in);
        the try {
            System.out.println ( "Enter a dividend:");
            int num1 = sc.nextInt ();
            the System. Out.println ( "enter a divisor:");
            int num2 = sc.nextInt ();
            int Result = num1 / num2;
        } the catch (exception E) {
            System.out.println ( "exception handling here!" );
        }
        System.out.println ( "end program run");

}

3.1.2 try-catch execution order of

The first is: do not encounter exceptions, namely the normal execution

The second: to match an exception

Code try {} is encountered abnormality, and will catch () abnormality in parentheses for comparison, if the code belongs to catch a catch block executes abnormality in the abnormality encountered, so execution try- behind the catch block codes

Third: not match an exception

 

<!--[if !supportLists]-->3.2  <!--[endif]-->try-catch-finally

try{} 代码块用于执行可能存在异常的代码,catch{}代码块用于捕获并处理异常。

finally{} 代码块用于回收资源(关闭文件、关闭数据库、关闭管道)的代码。finally代码块不管是否出现异常,都必须���行( finally块唯一不执行的情况System.exit(0) jvm正常退出。

3.1.1 try-catch-finally的执行顺序

第一种:catch块没有return语句

(1)没有遇到异常:

try块内的代码——>finally块内的代码——>finally块后的代码

(2)遇到异常并匹配到异常:

try块内的代码——>catch块内的代码——>finally块内的代码——>finally块后的代码

public class Test01 {
    public static void main(String[] args) {
        try {
            int a=1/0;
            System.out.println("try");
        } catch (Exception e) {
            System.out.println("catch");
        }finally {
            System.out.println("finally");
        }
        System.out.println("程序正常运行结束");
    }
}

结果:

1 catch
2 finally
3 程序正常运行结束

(3)遇到异常却没有匹配到异常:

try块内的代码——>finally块内的代码——>程序中断运行

public static void main(String[] args) {
    try {
        int a=1/0;//会抛出ArithmeticException
        System.out.println("try");
    } catch (NullPointerException e) {
        System.out.println("catch");
    }finally {
        System.out.println("finally");
    }
    System.out.println("程序正常运行结束");
}

结果:

1 Exception in thread "main" finally
2 java.lang.ArithmeticException: / by zero
3     at Test1.Test01.main(Test01.java:8)

第二种:catch块有return语句

(1)没有异常

try块内的代码——>finally块内的代码——>try块内的return语句

public class Test01 {
    public static int test() {
        try {
            int a=2*2;
            System.out.println("try");
            return a;
        } catch (Exception e) {
            System.out.println("catch");
            return 0;
        }finally {
            System.out.println("finally");
        }
    }
    public static void main(String[] args) {
        System.out.println(test());
        System.out.println("程序正常运行结束");
    }
}

结果:

1 try
2 finally
3 4
4 程序正常运行结束

(2)遇到异常并匹配到异常:

执行顺序如图:

 

public class Test01 {
    public static int test() {
        try {
            int a=2/0;
            System.out.println("try");
            return a;
        } catch (Exception e) {
            System.out.println("catch");
            return 0;
        }finally {
            System.out.println("finally");
        }
    }
    public static void main(String[] args) {
        System.out.println(test());
        System.out.println("程序正常运行结束");
    }
}

结果:

1 catch
2 finally
3 0
4 程序正常运行结束

(3)遇到异常却没有匹配到异常:

try块内的代码——>finally块内的代码——>程序中断运行

public class Test01 {
    public static int test() {
        try {
            int a=2/0;
            System.out.println("try");
            return a;
        } catch (NullPointerException e) {
            System.out.println("catch");
            return 0;
        }finally {
            System.out.println("finally");
        }
    }
    public static void main(String[] args) {
        System.out.println(test());
        System.out.println("程序正常运行结束");
    }
}

结果:

finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Test1.Test01.test(Test01.java:8)
    at Test1.Test01.main(Test01.java:19)

4. 声明异常

4.1 throws

当开发者在定义方法时,事先知道方法在调用时会出现异常,但不知道该如何处理,此时可以在该方法上声明异常。表示该方法在调用过程中会出现异常,请调用者自行处理。

在java中使用throws 声明异常。一个方法可以声明多个异常,用,号分割,写法如下:

1 public void test2()throws IOException,RuntimeException{
2         //有异常出得代码,在此处没有处理
3     }

4.2 声明异常与方法重载的关系

声明异常和方法重载没有任何关系。

4.3 声明异常与方法重写的关系

  • 如果父类方法声明了异常(检查时或运行时),子类方法可以完全遵循父类异常,也可以不声明异常。
  • 如果父类方法没有声明异常,子类可以不声明异常,也可以声明RuntimeException,但不能声明Exception。
  • 如果父类声明了运行时异常,子类可以完全遵循父类异常,也可以不声明异常。

5.抛出异常

当系统异常满足不了开发需要时,开发者可以自行根据需要自行抛出异常。

throw 用于手动抛出异常。

如果一直都没有处理(即没有用try-catch等语句)异常会把异常抛给调用者,一直抛到main函数处,如果在main函数中也没有处理继续在main函数后抛出异常,这时候会抛给jvm处理。如下栗子:

public class Test01 {
    public static void test1()throws IOException,RuntimeException{
        //有异常抛出得代码,在此处没有处理,例如:throw new Exception(“异常信息”);
    }
    public static void test2()throws IOException,RuntimeException{
        test1();//调用有抛出异常的方法,在此没有处理
    }
    public static void main(String[] args)throws IOException,RuntimeException {
        test2();//main调用有抛出异常的方法,在此没有处理
    }
}

注意:

开发者根据自身需要可以选择抛出检查时异常和运行时异常

6. 自定义异常

当JDK 中的异常类型不能满足程序的需要时,可以自定义异常类。

自定义异常步骤:

  • [1] 确定异常类型.继承Excepion 或者RuntimeException
  • [2] 编写自定义异常类,并实现构造方法
  • [3] 在方法需要的地方手动声明并抛出异常。

public class myException extends Exception {

    public myException() {
        super();
    }

    MyException public (the Message String) {
        Super (the Message);
    }
   
    // custom exception of methods to meet the needs of their
    public void showInfo () {
        System.out.println (super.getMessage () + "@ Line:" );
    }
}

Guess you like

Origin www.linuxidc.com/Linux/2019-08/160193.htm