Many programmers for many years did not grasp exception handling skills and principles

The exception mechanism in Java means: when the program encountered an unexpected condition during operation will automatically throw an Exception object to the notification procedure, the program after receiving the exception notification process can take a variety of measures, this mechanism enables the program more robust, more readable. This article Laijiangjiang knowledge exception handling.


Abnormal classification

Java Exception and RuntimeException into CheckedExcep.

  • RuntimeException: error occurs during program execution, will be checked exception. For example: the type of conversion errors, array subscript access violation, a null pointer exception, and so can not find the specified class.
  • CheckedException: exceptions are checked exceptions from Exception and not running, the compiler will enforce its capture by check and try-catch block or declare this exception is thrown to the caller processing method in the head.

2. Error and abnormal difference

Speaking Exception, often involve Error. And there is a distinction Error Exception:

Error refers to errors in the system, the programmer can not be changed and the processing is an error in the program compile time, it can only be corrected by modifying the program. Error in Java generally refers to the problems associated with the virtual machine, such as a system crash, the virtual machine error, insufficient memory space, the method call stack overflow. For applications such errors lead to disruption, relying on the program itself and can not be recovered and prevention, encounter such errors, we recommend the program to terminate, adjust the parameters of the virtual machine code or re-start the program;

Exception (exception) is a program can handle. When such abnormal, the programmer should capture as much as possible to handle exceptions, the program resumes, and should not be free to terminate an exception. Really do not know how to handle this exception is thrown upward left to deal with the caller.

3. The principle of exception handling

4. How custom exception

In the complex business environment, java comes exception may not meet the needs of our business, we may be an exception this time to process the custom business exceptions.

public class MyException extends RuntimeException {

    private static final long serialVersionUID = 6958499248468627021L;
   
    private String errorCode;
    
    private String errorMsg;

    public MyException(String errorCode,String errorMsg){
        super(errorMsg);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public MyException(String errorCode,String errorMsg,Throwable throwable){
        super(errorCode,throwable);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}

In use MyException, preferably define a class enumerator to enumerate error code and error details.

5. return and finally the execution order of

In Java, exception handling is mainly composed of try, catch, throw, throws and finally5 keywords processed. Java programs, if the abnormal, but not caught try-catch block, the system will throw an exception has been to the top, knowing encountered handling code. If the block has not been processed, it is thrown into the top, if it is multi-threaded () thrown by Thread.run, if it was a single-threaded main () throws. After the throw, if the child thread, the child thread exits. If an exception is thrown by the main program, then this whole program will quit.

A more common exception handling process is as follows:

    try {
        //step1
        System.out.println("try...");
        throw new RuntimeException("异常1...");
    }catch (Exception e){
        //step2
        System.out.println("catch。。。");
    }finally {
        //step3
        System.out.println("finally。。。");
    }
    //step4
    System.out.println("end...");

Due to the above code was successfully catch exceptions thrown live, so the current thread will not end, the program will continue down, step4 this step code will be printed out.

    try {
        System.out.println("try...");
        throw new RuntimeException("异常1...");
    }catch (Exception e){
        System.out.println("catch。。。");
        throw new RuntimeException("异常2...");
    }finally {
        System.out.println("finally。。。");
    }
    System.out.println("end...");

The above code, because the catch block threw an exception, and the exception is not appropriate catch block processing, the system will throw up this anomaly, the last print statement also less than execution.

try, catch, finally, throw and throws using induction

  • try, catch, and finally can not be used alone, can only try-catch, try-finally or try-catch-finally.
  • try block monitor code, abnormal stop executing the following code, and then transferred to an exception catch block to handle, after the catch block executing the code that will continue down the implementation .
  • finally block code will be executed, commonly used in resource recovery.
  • throws: an unusual statement, informing the caller method.
  • throw: throw an exception, as the exception is caught or continue to throw nothing to do with it.

There is also a more important is the implementation of the relationship between return and finally, you can refer to this blog

6. Abnormal chain

In the usual development, we will often catch an exception is thrown after another custom exception, and want to preserve the original exception information, which is called exception chain. When we custom exception, as long as a throwable receiving constructor parameters can be:

public MyException(String errorCode,String errorMsg,Throwable cause){
    super(errorCode,cause);
    this.errorCode = errorCode;
    this.errorMsg = errorMsg;
}

7. try-with-resources

We know that in the Java programming process, if you open the external resources (files, database connections, network connections, etc.), we must, after these external resources use, manually close them. JVM could not help because the external resource management, can not enjoy the JVM garbage collection mechanism, and if we do not ensure that the programming off the external resources at the right time, will lead to an external resource leaks, immediately there will be occupied by the file is abnormal, excessive database connection cause a lot of serious problems connected overflow pool.

  1. Traditional resource-off mode
//这种方式关闭资源,代码显得比较臃肿
public static void main(String[] args) {
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(new File("test"));
        System.out.println(inputStream.read());
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}
  1. try-with-resources way to close the resource
public static void main(String[] args) {
    try (FileInputStream inputStream = new FileInputStream(new File("test"))) {
        System.out.println(inputStream.read());
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

It will create the object's handle external resources in a try keywords in brackets after it, when the try-catch block is finished, Java will ensure that external resources close method is called. Code is not the moment many simple!
When an object handle external resources to achieve the AutoCloseable interface in JDK7 can use try-with-resource more elegant syntax shut resources, eliminate plate code.

reference

Guess you like

Origin www.cnblogs.com/54chensongxia/p/12146161.html