preface

This article is based on the author’s own degree of learning to talk about Java exceptions and their general processing methods. What is an exception?

Java exception classification and structure diagram

An exception is an unexpected event that occurs when a Java program is running and prevents the program from executing as expected.

1.Throwable

The Java standard library has some generic exceptions built into it, and these classes have Throwable as their top-level parent. All exceptions are inherited from Throwable and are the common ancestor of all exceptions.

2.Throwable has two subclasses, Error and Exception.

1.Error

The Error class, and instances of its subclasses, represent errors in the JVM itself. Errors cannot be handled by programmers in code, and errors are rare. Therefore, programmers should focus on the various Exception classes that branch off of Exception as a parent.

2.Exception

Exception, and its subclasses, represent various unexpected events sent by the program while it is running. Can be used by the Java exception handling mechanism, is the core of exception handling.

Classification of exception handling requirements based on Java.

1.Unckecked exception

Non-check exception. Error and RuntimeException and their subclasses. Javac does not raise or find such exceptions at compile time and does not require the program to handle them. So we can write code to handle (using try… The catch… Finally) can also be left unhandled. For these exceptions, we should fix the code rather than handle them through an exception handler. Such exceptions are most likely due to poorly written code. Such as zero error ArithmeticException, casts error ClassCastException error, array index ArrayIndexOutOfBoundsException seams, NullPointerException and so on.

2.Checked Exception

Check for exceptions. Exceptions other than Error and RuntimeException. Checkable exceptions, which are very common when coding, all checked exceptions need to be handled in your code. Their occurrence is predictable, normal, and reasonably manageable. Java forces the programmer to do preparatory work for such exceptions (using try… The catch… Finally or throws). The compilation fails if it is either caught and processed in a try-catch statement or thrown with a throws clause declaration in a method. Such exceptions are usually caused by the environment in which the program is running. Because programs can be run in all kinds of unknown environments, and the programmer has no way of interfering with how the user uses the program, the programmer should always be prepared for such exceptions. Such as SQLException, IOException, ClassNotFoundException, etc.

chart

Exception handling

When writing code to handle exceptions, there are two different ways to handle checking for exceptions: use try… The catch… The finally statement block handles it. Alternatively, use the throws declaration in the function signature and leave it to the function caller to resolve.

The try… The catch… finally

block

Try {// put code in the try block that may have an exception. // If the try is complete and no exception occurs, then the finally block and the code after finally (if any) are executed. // If an exception occurs, try to match the catch block. } Catch (SQLException SQLException){// Each catch block is used to catch and process a particular exception, or a subclass of that exception type. In Java7, you can declare multiple exceptions in a catch. // The parentheses after catch define the exception type and the exception parameters. If the exception matches and is matched first, the virtual machine will use the catch block to handle the exception. // In a catch block, you can use the exception parameters of the block to get information about the exception. Exception parameters are local variables in the catch block and cannot be accessed by other blocks. // If the exception that occurred in the current try block is not caught in any subsequent catch, finally is executed, and then outside the functioncallerTo match the exception handler. If no exception occurs in the try, all catch blocks are ignored. }catch(Exception exception){ //... }finally{// Finally blocks are usually optional. // Finally executes regardless of whether an exception occurs and if an exception match is handled. // A try must have at least one catch block, otherwise, at least one finally block. But finally is not used to handle exceptions, and finally does not catch exceptions. // Finally does some cleanup work, such as stream closure, database connection closure, etc. }Copy the code

Something to watch out for

1. Local variables in try blocks, local variables in catch blocks (including exception variables), and local variables in finally may not be shared.

2. Each catch block is used to handle an exception. Exception matching is found from the top down in the order of the catch blocks, and only the first matching catch is executed. When matching, not only does exact matching run, but parent matching is also supported. Therefore, if multiple catch types under the same try block have a parent-child relationship, you should put the subclass exception first and the parent exception last to ensure that each catch block has a meaning.

3. In Java, the task of exception handling is to move the flow of execution control from where an exception occurs to where it can be handled. In other words, when a statement of a function fails, the following statement is not executed, and it loses focus. The flow of execution jumps to the nearest matching exception handling catch block. Once the exception is handled, the flow of execution continues after the catch block that handled the exception.

public static void main(String[] args){ int a=8/0; // The exception throws a point system.out.println ("Handling exceptions");
      
	}

Copy the code

public static void main(String[] args){ try { int a=8/0; Catch (ArithmeticException e) {system.out.println (arithmeticmeticException e) {system.out.println ("Handling exceptions"); }}Copy the code

Finally block

The finally block does not care if an exception occurs; if the corresponding try executes, it must also execute. There is only one way for a finally block not to execute: system.exit (). So finally blocks are often used to do resource release operations: close files, close database connections, and so on.

Good programming practice is to open resources ina try block and clean up and release them ina finally block.

Points to note:

1. The finally block has no ability to handle exceptions. Exceptions can only be handled by catch blocks.

2, In the same try… The catch… In a finally block, if an exception is thrown ina try and there is a matching catch block, the catch block is executed first and then the finally block is executed. If there is no catch block match, then finally is executed and the caller outside is searched for an appropriate catch block.

3, In the same try… The catch… In a finally block, if an exception occurs ina try and an exception is thrown in the matching catch block, then the finally block is executed: first, the finally block is executed, and then the enclosing caller looks for the appropriate catch block.

Throws function declaration

Throws Declaration: If the code inside a method throws checked exceptions and the method itself does not fully handle them, Java guarantees that you must declare these possible exceptions on the method signature using the throws keyword. Otherwise, the compiler will fail.

Throws is another way of handling exceptions, which is different from try… The catch… Finally and throws only declare the exceptions that may occur ina function to the caller, but do not handle them themselves.

The reason for this exception handling may be that the method itself does not know how to handle such an exception, or that it is better handled by the caller, who is responsible for any exceptions that may occur.

Public void throwBibi() throws ExceptionType1, ExceptionType2,ExceptionTypeN {/*throwBibi internally throws ExceptionType1. ExceptionType2, exception objects of the ExceptionTypeN class, or their subclasses. * /}Copy the code

Unchecked exception: Error, RuntimeException, or a subclass of them. You can declare exceptions to throw without using the Throws keyword, and the compiler will pass without exception, but will throw them at run time.

2. When an exception is thrown, the caller of the method must either handle it or rethrow it.

3. When a subclass overrides a method that its parent throws, the exception declared must be the same class or subclass of the exception declared by the parent method.

Throw Throws the throw exceptionObject statement

A programmer can also explicitly throw an exception manually by using a throw statement. The throw statement must be followed by an exception object.

The throw statement must be written in the function, and the place where the throw statement is executed is an exception throw point, which is no different from the exception throw point automatically formed by the JRE.

public void save(User user)
{
      if(user  == null) 
          throw new IllegalArgumentException("User object is empty"); / /... }Copy the code

Throws throws

Throw is used in the body of a method, as the code above shows, directly inside the body of a method. Throws throws throw throws are followed by method declarations and are handled by the caller of the method.

2. A throw is an exception instance that is specifically thrown. Throws declares what type of exception its caller can catch.

Throw, if executed, then some kind of exception must be thrown, but throws indicates that it may occur, but not necessarily.

Throws appears in the function header and throws in the function body. The two types are not processed by the function. The real processing is handled by the upper call of the function.

Custom exception

A custom exception is a class that extends from the Throwable class or its subclasses.

You can use Java’s built-in exception classes to describe most exceptions that occur during programming, and you can also use custom exceptions to describe the types of exceptions generated by a particular business.

If you want to customize an Exception class, you simply extend the Exception class, so that custom exceptions are checked exceptions. If you want to customize non-check exceptions, extend from RuntimeException.

By international convention, a custom exception should always contain the following constructor:

A constructor with no arguments. A constructor that takes a String argument and is passed to the constructor of the parent class. A constructor that takes a String argument and a Throwable argument is passed to the parent constructor.

Here is the IOException class complete source code, can be used for reference.

public class IOException extends Exception
{
    static final long serialVersionUID = 7818375828146090155L;
 
    public IOException() { super(); } public IOException(String message) { super(message); } public IOException(String message, Throwable cause) { super(message, cause); } public IOException(Throwable cause) { super(cause); }}Copy the code

1. When a subclass overrides a function with a throws declaration of its parent class, the exception declared by the subclass must be within the bounds of the parent exception. The exception handler used to process the parent class’s throws method must also apply to the subclass’s method with throws. This is to support polymorphism.

For example, if a superclass method throws two exceptions, a subclass cannot throw three or more exceptions. The parent class throws IOException, and the subclass must throw IOException or a subclass of IOException.

2. Java programs can be multithreaded. Each thread is a separate flow of execution, a separate stack of function calls. If the program has only one thread, exceptions that are not handled by any code cause the program to terminate. If it is multithreaded, exceptions that are not handled by any code simply cause the thread in which the exception was created to terminate.

That is, exceptions in Java are thread-independent and should be handled by the thread itself, not delegated externally, and not directly affecting the execution of other threads.

Chain of exceptions

In large, modular software development, we sometimes catch one exception and then throw another. In this way, the cause of the occurrence of the exception is transmitted one by one, that is, the bottom of the abnormal information to the upper layer, so thrown layer by layer, called the exception chain.

Exception chain: Construct a new exception object that takes an exception object as an argument. The new foreign object will contain information about the previous exception. This technique is implemented primarily as a function of the exception class with a Throwable parameter. This parameter exception, we call it a cause.

The Throwable class source code contains a Throwable field cause, which holds the root exception parameter passed during construction. This design is similar to the node class design of the linked list, so the formation of the chain is also natural

public class Throwable implements Serializable { private Throwable cause = this; public Throwable(String message, Throwable cause) { fillInStackTrace(); detailMessage = message; this.cause = cause; } public Throwable(Throwable cause) { fillInStackTrace(); detailMessage = (cause==null ? null : cause.toString()); this.cause = cause; } / /... }Copy the code

Here is an example that demonstrates the chain of exceptions: Enter two ints from the command line, add them together, and print. If the input number is not an int, getInputNumbers will result in an exception, which will result in an add exception, and a chained exception can be thrown in the add.

public static void main(String[] args)
{
 
    System.out.println("Please enter two addends.");
    int result;
    try
    {
        result = add();
        System.out.println("The results."+result); } catch (Exception e){ e.printStackTrace(); Private static List<Integer> private static List<Integer>getInputNumbers()
{
    List<Integer> nums = new ArrayList<>();
    Scanner scan = new Scanner(System.in);
    try {
        int num1 = scan.nextInt();
        int num2 = scan.nextInt();
        nums.add(new Integer(num1));
        nums.add(new Integer(num2));
    }catch(InputMismatchException immExp){
        throw immExp;
    }finally {
        scan.close();
    }
    returnnums; Private static int add() throws Exception {int result; try { List<Integer> nums =getInputNumbers(); result = nums.get(0) + nums.get(1); }catch(InputMismatchException immExp){ throw new Exception("Calculation failed",immExp); // chain: Construct a new exception object that takes an exception object as an argument. }return  result;
}

Copy the code

The results of

conclusion

During the execution of a program, unexpected occurrences, deviations from the intent of our program, can be understood as exceptions.

The exception mechanism provided by Java can improve the robustness of programs, which is a foundation that must be mastered in the process of Learning Java.

Just a brief talk, there may be omissions or mistakes, hope understanding.

May your head not be bald