omg

Because the program exception handling problem, just a few days ago Long Uncle’s service hung up for a few seconds.

Finished, immediately at the end of the quarter hit performance, unexpectedly overturned here, heart wrung.

It doesn’t affect the user experience, but finding problems and fixing them is part of an engineer’s daily pursuit.

As a good engineer, I should add a few points:

  • Get to the bottom of the problem
  • Summarize the cause of the problem
  • To prevent similar mistakes

Exception handling is familiar to every developer.

As one person describes it, “A developer spends 90% of his time handling exceptions.”

That’s not a bad thing to say, because normal logic is easy to write, and exception handling takes up most of the developer’s time.

Since it takes up so much of our development time, why not take the initiative to spend some time to get to know him, get to know him, don’t let him become the most familiar stranger.

The article Outlines

Abnormal classification

In Java, exceptions are divided into checked exceptions and runtime exceptions. Both are in the exception class hierarchy. The following figure shows the inheritance of Java exception classes.

It’s not hard to see that all exceptions inherit from a common parent class, Throwable, and Throwable has two important subclasses: Exception and Error.

Error (Error)

Engineers are most afraid of Error. When I see Error and FAIL are three laps too big, I feel that Error always makes trouble for me.

Error refers to internal errors and resource exhaustion errors in the Java runtime system.

Applications should not throw objects of this type.

If such an internal error occurs, nothing can be done except to notify the user and try to make the program terminate safely. This is rarely the case.

This error can cause your program to run daily and suddenly die one day.

Exception

Exceptions refer to unexpected conditions, such as file failure, network connection failure, and invalid parameters.

An exception is an event that occurs during program execution and interferes with the normal flow of instructions.

Java describes various exceptions through a number of subclasses of the Throwable class in the API. Thus, Java exceptions are objects, instances of Throwable subclasses that describe error conditions that occur in a piece of code.

When a condition is generated, an error will throw an exception.

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

Exceptions are mainly divided into runtime exceptions and non-runtime exceptions (compile exceptions)

Run-time exceptions are very well understood, when a program is running around and something triggers that causes an exception to happen. Out of bounds, NullPointerException, etc.

Compile-time exceptions are exceptions thrown when a program is compiled, for example, the accessed file does not exist. This type of exception is easy to avoid, the compile will not pass, and the program will not run until it is resolved.

Of course, some people also classify exceptions as checkable and uncheckable.

A checkable exception is also called an exception that the compiler requires to be handled. Generally, the compiler checks for it and either catches it or throws it, or it must be handled.

What the compiler cannot check, the programmer must actively check, and then dispose of it.

It doesn’t matter how you classify it, it depends on the situation you’re in, but ultimately it’s all about understanding the exception and dealing with it.

Exception handling mechanism

Now that you know what Java exceptions are and what they are, let’s talk about the mechanisms that handle them.

The figure-eight policy throws an exception and catches an exception

The throw statement is used to throw exceptions, and the throws statement is used to declare exceptions that may occur.

Here’s an example:

 public  Integer division(int x, int y) {
        if (y == 0)
            throw new ArithmeticException("Throw an arithmetic exception"); // Throw an exception
        return x / y;
 }
Copy the code

Throws an exception rule:

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 passing, but will throw them at run time.

2) You must declare any checked exceptions that the method can throw. If a method is likely to have a traceable exception, it is either caught with a try-catch statement or thrown with a throws clause declaration, otherwise a compilation error will occur

3) The method caller must handle or rethrow an exception only if it is thrown. When the method caller is unable to handle the exception, it should continue to throw rather than swallow it.

4) The calling method must follow the rules for handling and declaring any observable exceptions. If you override a method, you cannot declare exceptions that are different from the override method. Any exception declared must be a class or subclass of the exception declared by the overriding method.

Java uses try-catch-finally statements to catch and handle exceptions.

try{
    // Code that may generate an exception
}catch (Exception e){
  // Exception handling logic
}
Copy the code
try{
    // Code that may generate an exception
}catch (Exception e){
  // Exception handling logic
}finally {
  // The logic that must be executed
}
Copy the code

This grammar we should be familiar with, forget it, long uncle or wordy again.

Try block: This block is used to catch and handle exceptions that might be raised in code that normally does what the program should do.

Catch block: This block is used to catch and handle exceptions generated in the try block.

Each catch block declares a particular type of exception that it can handle, which is the exception of that particular type in parentheses after the catch.

Before Java 7, each the catch block can only catch an exception, since Java 7 support a catch to capture a variety of abnormal, with a | between multiple exceptions.

try{
            // Code that may generate an exception
        }
        catch(Exception1 | Exception2 |... | Exception_n e1){
            // Exception code for unified handling
        }
        finally{
            // This is usually code that frees resources
        }
Copy the code

Finally block: Statements ina finally block are executed whether or not exceptions are caught or handled. When a return statement is encountered ina try or catch block, the finally block is executed before the method returns.

A finally block is not executed in four special cases:

1) An exception occurred in the finally statement block. 2) Use system.exit () in the previous code to exit the program. 3) The thread in which the program resides dies. 4) Turn off the CPU.

Try, catch, finally block execution order:

Java exception processing execution order

Here we basically understand how to come to the exception, how to deal with, next to say a common exception masking problem.

In general, possible exceptions are caught ina try, handled by a catch, and some resource closing is done in finally.

There’s nothing to be said for normal circumstances, but I’m not afraid of abnormal ones.

Here’s an example:

try{
            // Code that may generate an exception
        }
        catch(Exception1 | Exception2 |... | Exception_n e1){
            // Exception code for unified handling
        }
        finally{
            // This is usually code that frees resources
          in.close();
          out.close();
        }
Copy the code

Do you write this everyday? It seems normal.

What if our finally statement block also throws an exception?

    public Integer division(int x, int y) throws Exception {
        try{
            return x/y;
        }catch (ArithmeticException e){
            System.out.println(e.getMessage());
            throw new ArithmeticException("Arithmetic anomaly");
        }finally {
            System.out.println("Release resources");
            throw new Exception("Resource release exception"); }}Copy the code

For example, this code, intended to throw an arithmetic exception, throws a free resource exception.

Due to the loss of exception information, exception masking can cause some bugs to become extremely difficult to find, which can lead to a mental breakdown.

This is a masked exception, how to solve this masked exception?

Someone looked at the code above and found another problem. Will the finally statement be executed when there is a return statement in the try?

That’s a good question, and the answer is that it executes, and it executes before the method returns to the caller.

Resolve the masking exception problem

The new try-with-Resource syntax sugar in Java 1.7 addresses this problem of exception masking caused by closing resources.

 public void testExcep(a){
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(new File("in.txt")));
            out = new BufferedOutputStream(new FileOutputStream(new File("out.txt")));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(in ! =null) {
                    in.close();
                }
                if(out ! =null) { out.close(); }}catch(IOException e) { e.printStackTrace(); }}}Copy the code

In order to free up resources, we have to write this. But when we’re familiar with the try-with-resource syntax, we can write it like this.

public static void main(String[] args) {
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("in.txt")));
             BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
            // Process input data and output
        } catch (IOException e) {
            // Catch the exception and handle it}}Copy the code

In the try clause, you can create a resource object that is automatically closed by the runtime after the program finishes a try-catch.

The code is simple to write and will also solve the problem of masking exceptions.

Of course, it is important to understand the implementation logic inside the resource’s close method when using a try-with-resource. Otherwise, resources may still leak.

How about that? Is that easy? I learned that we’re going to play pussy together

Common Abnormal Problems

Arithmetic exception class: ArithmeticExecption

NullPointerException class: NullPointerException

Type casting exception: ClassCastException

Array negative index exception: NegativeArrayException

Array subscript cross-border exception: ArrayIndexOutOfBoundsException

File terminated Exception: EOFException

FileNotFoundException: FileNotFoundException

String conversion to number exception: NumberFormatException

Operation database exception: SQLException

Input/output exception: IOException

Method found no abnormality: NoSuchMethodException

These are very common exceptions, but there are other exceptions that you should summarize in your daily work and write in your little book.

That’s all for today’s content, please remember to like 👍 if you are helpful.

I’m Uncle Long, and we’ll see you next time at ✌️.