On abnormal

 

1. Overview of abnormal

What is unusual

Is an event that occurred during program execution, it interrupts the normal flow of a program instruction being executed. To handle errors in the program run timely and effective, you must use the exception class

Exception class

  • Java exception information in the package into a class
  • When an exception occurs the program will create an exception class object and throw an exception related information (such as abnormal position, the reason)

Common exceptions

  • Array bounds exception: ArrayIndexOutOfBoundsException
  • Null pointer exception: NullPointerException
  • Abnormal count to divide by 0: ArithmeticException: / by ZERO

2. The difference between the inheritance system abnormalities and errors

Unusual succession system

In Java exception types are all built subclasses of class java.lang.Throwable class, that is located on top of the hierarchy of the Throwable exception class

Error Exception has two branches and class Throwable as shown at FIG.

FIG known, Throwable class is the superclass of exceptions and errors, and the following Error Exception has two subclasses represent errors and exceptions. In which abnormal and non-runtime exceptions, these two anomalies are very different exception classes Exception divided into operation, also known as no abnormalities (Unchecked Exception) and abnormalities (Checked Exception)

  • Runtime exceptions : all RuntimeException class and its subclasses abnormality, such as a NullPointerException , an IndexOutOfBoundsException etc. These abnormalities are not checked exception, capturing processing program may be selected, or may not handle. These abnormalities typically caused by a logic error, the program should be avoided as much as possible from a logical point of such an abnormality occurs.
  • Non runtime exception: means RuntimeException abnormal outside, belong to the class and its subclasses Exception 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 , a ClassNotFoundException like as well as user-defined exception Exception,

The difference between anomalies and errors

 

abnormal

  • Refers to the program at compile time, runtime trouble has occurred, we can deal with exceptions
  • If it does not handle the exception, the program will end
  • He cited the example
public static void main(String[] args) {
        int[] arr = {1,2,3};
        System.out.println(arr[3]);
        //该句运行时会发生数组越界异常ArraylndexOutOfBoundException
        //由于没有处理异常,导致程序无法继续进行,无法打印程序结束
        System.out.println("程序结束");
}

 

error

  • Description Java runtime internal error or resource exhaustion error (only terminate the program)

  • Error The occurrence of errors are often system-level problems are occurring systems where the JVM, and feedback to the JVM 

  • Not for treatment, can only modify the code

  • He cited the example

public static void main(String[] args) {
        int array[] = new int[1024*1024*1024];
        //该句运行时JVM无法分配足够的空间,发生了内存溢出错误OutOfMemoryError
        //程序也会立即结束,不会打印程序结束
        System.out.println("程序结束");
}

3. The exception object causes and treatment

The reasons of unusual objects

for example

class ArrayTools{
    //对给定的数组通过给定的角标获取元素。
    public static int getElement(int[] arr,int index)	{
        int element = arr[index];
        return element;
    }
}
public class Test {
    public static void main(String[] args) 	{
        int[] arr = {34,12,67};
        int num = ArrayTools.getElement(arr,4);//静态方法用类名调用,不依赖于对象
        System.out.println("num="+num);
        System.out.println("程序结束");
    }
}

Cause Analysis

  • 4 Because no index was found, leading to a run-time exception. This exception JVM know: ArrayIndexOutOfBoundsException  exception Java itself has described: name of the exception, abnormal contents, resulting in an abnormal position
  • These Java object encapsulates information, new new An ArrayIndexOutOfBoundsException (. 4) exception thrown JVM generated caller main () method
  • main () method receives the array index bounds exception object. Since the main () method does not perform exception handling, main () method will continue to be an exception thrown to the caller JVM
  • When the JVM receive an exception, the name of the exception object, abnormal contents, on location are displayed on the console. While allowing the program terminates immediately

Unusual approach

JVM's default processing method

  • The name of the exception, reason, location and other information in the console output, while an immediate end to the program
  • Once an exception occurs, the code will no longer continue down

Settlement Procedures manual abnormal

  • Write code try...catch...finally
  • Throw out throws

4. The method throws an internal target throw keyword

In java, providing a throwkey, which is used to throw an exception object specified

When using the throw keyword?

When you call a method using the parameters received, first of all need to determine the legal parameters of the data, the data if legitimate, they should tell the caller, transfer the data to come in legally. Then you need to use throwing an exception to tell the caller.

Use throwthe keyword specific operation

  • Create an exception object, package some tips (you can write your own message)
  • By keyword throw this exception object to inform to the caller. throw exception object
  • throw used in the method, the object to throw an exception, the exception pass the object to the caller, and ends the current execution of the method

throw keyword format

  • throw new Exception class name (parameters)
  • eg: throw new NullPointerException ( "array is null");
  • eg: throw new ArrayIndexOutOfBoundsException ( "array bounds");

5. The method of statement throws an exception keyword

statement

The problem that may arise out of the identification, reporting to the caller. If the internal methods throw an exception, and not the capture process (explained later in this section) throws a compiler, it must throws declare, let the caller to deal

Unusual statement format

Back modifier value type method name (parameter) throws exception classes 1, 2 ... exception classes {}

Precautions :

If the method may be a variety of exception, can throws write multiple exception classes after keywords, separated by commas

6.try ... catch exception handling

capture

Java in the statement of abnormal targeted for capture, processing may be abnormal occurrence of the specified property

Capture unusual format

        try{
               //需要被检测的语句(可能出现异常的语句)
        }
        catch (异常类 变量) {
               //异常的处理方式
        }
        finally{
               //一定会被执行的语句
        }

Format Description

  • try: The code block may be an exception statement
  • catch: used to capture some abnormality, the abnormality to achieve capture processing
  • finally: Code of this section is sure to be executed. Abnormal presence would no longer lead to code execution, while some specific code regardless of whether an abnormal, need to be performed
  • try ... catch ...  after handling exceptions, the program will continue 

Multi-catch processing

The plurality of try catch composition

Abnormality detecting code, and transmitted to the abnormality detection processing catch. Abnormal information for each different capture process

Multi-format processing of catch

Note: When capturing exception handling, there is also scope variables, can be defined as a plurality of variable names exception e 

    void show() { //不用throws
        try{
            throw new Exception();//产生异常直接捕获处理
        }
        catch (XxxException e) {
            //处理方式
        }
        catch (YyyException e) {
            //处理方式
        }
        catch (ZzzException e) {
            //处理方式
        }
        finally{
            //处理方式
        }

Multi-catch processing details

  • Multiple catch parentheses, write the name of the class exception class, there is no effect on order.
  • Same level exception: between exception class thrown, no inheritance, no order
  • Superior-subordinate relationship exception: the more senior of the parent, the more write below

7.finally block

Features of the finally block

The  finallycontrol body will execute statement

finally the role

finallyRegardless of whether there is abnormal procedures, procedures must be performed to release resources, such as: IO stream operations and database operations will see

8. The characteristic abnormality during the operation

 

Overview of abnormal operation period

RuntimeException and his all belong to a subclass abnormal operating period

NullPointerException, ArrayIndexOutOfBoundsException belong to abnormal operating period

Unusual runtime features

  • Method throws an exception during the run, no need to define the method throws a statement, the caller does not need to handle this exception.
  • Abnormal operation during the event, the need to modify the program source code.

9. custom exception

Custom exception definition

Reading the source code found: each exception are calling the parent class constructor, describing the abnormal transmission of information to the parent, so the parent class to help us encapsulate information about the exception

format

Class 异常名 extends Exception{ //或继承RuntimeException
    public 异常名(){
    }
    public 异常名(String s){ 
        super(s); 
    }
}

Custom exception of practice

  • There arg constructor in the Person class, the judge of age, the age is negative or greater than 200-year-old is thrown  NoAgeException an exception, the exception message "age numerical illegal"
  • In the test class, call the constructor have parameters, and complete the creation of the Person class objects, respond to abnormal processing

About constructor throws an exception summary

The constructor throws in the end this NoAgeExceptionis to inherit Exceptionit? Or inherit RuntimeExceptionit?

  • Inheritance Exception, we must throws statement, a statement to inform the caller capture, once the problem dealt with the caller's program will continue
  • Inheritance RuntimeExcpetion, no statement throws, then calls are captured without writing code, because the caller does not know there is a problem
  • Event NoAgeException, the caller program will be stopped, and there JVM will display information to the screen, allowing the caller to see the problem corrected code.

​​​​​​​

 

 

Published 20 original articles · won praise 9 · views 900

Guess you like

Origin blog.csdn.net/weixin_44915811/article/details/104235216