Solid Java Foundation Series 10: deep understanding of Java exception system

Time:2020-2-25

Catalog

  • Why use exceptions
  • Basic definition of exception
  • Anomaly system
  • Abnormal initial knowledge
  • Exceptions and errors
  • How to handle exceptions
  • “Irresponsible” throws
  • Tangled finally
  • Throw: a keyword used by JRE
  • Exception call chain
  • Custom exception
  • Abnormal precautions
  • When finally meets return
  • Java abnormal common interview questions
  • Reference articles
  • WeChat official account
    • Java technology
    • Official account number: Huang Xiaoxie

– Java anomaly

This series of articles will be organized into my “Java interview guide” warehouse on GitHub, and more highlights can be found in my warehouse

https://github.com/h2pl/Java-Tutorial

If you like, please point to star ha

The article started on my personal blog:

www.how2playlife.com

This article is one of the WeChat official account Java Java. This part of the content comes from the Internet. In order to make the topic clear and clear, it also integrates many of the content of the technology blog that I think is good, and draws some good blog articles. If there is any infringement, please contact the author.
This series of blog will tell you how to learn the basic knowledge of Java step by step from the beginning to the advanced stage, and then learn the implementation principle behind each java knowledge point, understand the whole Java technology system more completely, and form your own knowledge framework. In order to better summarize and test your learning results, this series of articles will also provide interview questions and reference answers for each knowledge point.

If you have any suggestions or questions, you can also pay attention to the official account of Java. Contact your author and welcome you to participate in the creation and revision of this series of blog posts. What’s what?

Why use exceptions

First of all, we can make it clear that the exception handling mechanism can ensure the robustness of our programs and improve the system availability. Although we don’t particularly like to see it, we can’t help but recognize its position and function.

When there is no exception mechanism, we deal with it as follows: judge whether an exception has occurred through the return value of the function (the return value is usually agreed), and the program calling the function is responsible for checking and analyzing the return value. Although exception problems can be solved, there are several defects in doing so:

1. Easy to confuse. If the return value of – 11111 indicates an exception, what happens when the final result of the program is – 1111?

2. Poor code readability. Confusing the exception handling code with the program code will reduce the readability of the code.

3. Calling functions to analyze exceptions requires programmers to have a deep understanding of library functions.

The exception handling mechanism provided in OO is a powerful way to provide robust code. Using exception mechanism can reduce the complexity of error handling code. If you do not use exception, you must check specific error and handle it in many places in the program.

If you use an exception, you don’t have to check at the method call, because the exception mechanism will ensure that you can catch the error, and you only need to handle the error in one place, that is, in the so-called exception handler.

This approach not only saves code, but also separates the code “outlining what to do during normal execution” from the code “what to do if something goes wrong”. In a word, compared with the previous error handling methods, the exception mechanism makes the reading, writing and debugging of the code more orderly. (from think in Java).

This part is selected from http://www.cnblogs.com/chenssy/p/3438130.html

Basic definition of exception

In think in Java, exceptions are defined as problems that prevent the current method or scope from executing. We must be clear here: the error of exception code to some extent. Although Java has exception handling mechanism, we can’t look at the exception from a “normal” perspective. The reason for the exception handling mechanism is to tell you that there may be or has been an error, your program has an abnormal situation, which may lead to program failure!

So when will an exception occur? Only in your current environment can the program run normally, that is to say, the program can’t solve the problem correctly, then it will jump out of the current environment and throw an exception. After throwing an exception, it does several things first.

First, it uses new to create an exception object, then terminates the program where the exception is generated, and pops up a reference to the exception object from the current environment. The exception handling mechanism takes over the program and starts to find a proper place to continue executing the program, which is the exception handler.

Generally speaking, the exception handling mechanism is that when an exception occurs in a program, it forces the program to stop running, records the exception information and feeds it back to us, so that we can determine whether to handle the exception or not.

Anomaly system

[failed to transfer pictures from the external chain (img-knxcbtk0-1569073569353) (https://image0.cnblogs.com/blog/381060/201311/22185952-834d92bc2bfe498f9a33414cc7a2c8a4. PNG))

As can be seen from the above figure, throwable is a superclass of all errors and exceptions in the Java language. It has two subclasses: error and exception.

The Java standard library has built in some common exceptions. These classes take throwable as the top-level parent class.

Throwable also derives the error class and exception class.

Error: an instance of the error class and its subclasses represents the error of the JVM itself. Errors cannot be handled by programmers through code, and errors are rare. Therefore, programmers should pay attention to all kinds of exception classes under the branch of which exception is the parent.

Exception: exception and its subclasses represent various unexpected events sent by the program runtime. It can be used by Java exception handling mechanism and is the core of exception handling.

In general, we divide the exception classes into two categories according to the processing requirements of javac.

Unchecked exception: error and runtimeException and their subclasses. When javac compiles, it will not prompt and find such exceptions, and it is not required to handle these exceptions in the program. So if you like, we can write code processing (using try Catch… Finally) such an exception can also not be handled.

For these exceptions, we should fix the code instead of dealing with it through the exception handler. Most of the reasons for such exceptions are due to code writing problems. For example, except 0 error arithmeticexception, wrong cast error ClassCastException, array index out of bounds arrayindexofboundsexception, null object NullPointerException, etc.

Checked exception: exceptions other than error and runtimeException. Javac forces programmers to prepare for such exceptions (using try Catch… Finally or throws). Either catch it with a try catch statement and process it in the method, or throw it with a throws clause declaration, otherwise the compilation will not pass.

Such exceptions are generally caused by the running environment of the program. Because the program may be run in various unknown environments, and the programmer cannot interfere with how the user uses the program he wrote, the programmer should be prepared for such an exception at all times. Such as sqlexception, IOException, classnotfoundexception, etc.

It needs to be clear that check and non check are for javac, so it is easy to understand and distinguish.

This part is from http://www.importnew.com/26613.html

Abnormal initial knowledge

The exception is raised when executing a function, and the function is called hierarchically, forming a call stack, because as long as a function has an exception, all its callers will be affected by the exception. When these affected functions are output with exception information, an exception tracking stack is formed.

The place where the exception first occurs is called the exception throw point.

Public class exception{
    public static void main (String [] args )
    {
        System. Out. Println ("---- welcome to the command line division calculator ----");
        CMDCalculate ();
    }
    public static void CMDCalculate ()
    {
        Scanner scan = new Scanner ( System. in );
        int num1 = scan .nextInt () ;
        int num2 = scan .nextInt () ;
        int result = devide (num1 , num2 ) ;
        System . out. println( "result:" + result) ;
        scan .close () ;
    }
    public static int devide (int num1, int num2 ){
        return num1 / num2 ;
    }

//---- welcome to the command line division calculator----
//            1
//            0
//    Exception in thread "main" java.lang.ArithmeticException: / by zero
//At com.javase. Exception.devide (exception. Java: 24)
//At com.javase. Exception.cmdcalculate (exception. Java: 19)
//At com.javase. Exception. Main (exception. Java: 12)

//---- welcome to the command line division calculator----
//    r
//    Exception in thread "main" java.util.InputMismatchException
//    at java.util.Scanner.throwFor(Scanner.java:864)
//    at java.util.Scanner.next(Scanner.java:1485)
//    at java.util.Scanner.nextInt(Scanner.java:2117)
//    at java.util.Scanner.nextInt(Scanner.java:2076)
//At com.javase. Exception.cmdcalculate (exception. Java: 17)
//At com.javase. Exception. Main (exception. Java: 12)

[failed to transfer pictures from the external chain (img-9rquqjqj-1569073569354) (http://incdn1.b0.upaiyun.com/2017/09/0b3e4ca2f4cf8d7116c7ad354940601f. PNG))

As can be seen from the above example, when the devide function has an exception except 0, the devide function will throw an arithmeticexception exception, so the call to its cmdcalculate function can not be completed normally, so it will also send an exception, and the caller – main of cmdcalculate, because the cmdcalculate throws an exception, also has an exception, so it always backtracks to the bottom of the call stack.

This behavior is called exception bubbling. The purpose of exception bubbling is to find the latest exception handler in the current function or the caller of this function. Since no exception handling mechanism is used in this example, the exception is finally thrown to JRE by the main function, resulting in program termination.

The above code does not use exception handling mechanism, and can also be compiled smoothly, because the two exceptions are non checking exceptions. But the following example must use the exception handling mechanism, because the exception is a check exception.

In the code, I choose to use throws to declare exceptions and let the caller of the function handle possible exceptions. But why only throws IOException? Because FileNotFoundException is a subclass of IOException, which is within the scope of processing.

Exceptions and errors

Here’s an example

//Errors are errors that the JVM can't handle
//Exception is a Java defined tool for simplifying error handling and locating errors.
Public class errors and errors{
    Error error = new Error();

    public static void main(String[] args) {
        throw new Error();
    }

    //The following four exceptions or errors have different handling methods
    public void error1 (){
        //The compile time requires that it must be handled, because this exception is the top-level exception, including the check exception, which must be handled
        try {
            throw new Throwable();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
    //Exception must also be handled. Otherwise, an error is reported, because the check exceptions are inherited from the exception, so they need to be caught by default.
    public void error2 (){
        try {
            throw new Exception();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //Error can not be processed and no error is reported when compiling. The reason is that the virtual machine can't handle it at all, so nothing needs to be done
    public void error3 (){
        throw new Error();
    }

    //RuntimeException is known to compile without error
    public void error4 (){
        throw new RuntimeException();
    }
//    Exception in thread "main" java.lang.Error
//At com.javase. Exception. Error. Main (error. Java: 11)

}

How to handle exceptions

When writing code to handle exceptions, there are two different handling methods for checking exceptions:

Use try… Catch… The finally statement block handles it.

Or, use the throws declaration in the function signature and give it to the function caller to solve it.

Here are some specific examples, including error, exception and throwable

The above example is a run-time exception that does not need to show the catch.
The following example is a checkable exception to show caught or thrown.

@Test
public void testException() throws IOException
{
    //FileNotFoundException will be thrown by the constructor of FileInputStream
    FileInputStream fileIn = new FileInputStream("E:\a.txt");

    int word;
    //The read method throws an IOException
    while((word =  fileIn.read())!=-1)
    {
        System.out.print((char)word);
    }
    //The close method throws an IOException
    fileIn.close();
}

Try catch finally

Public class exception handling method{

@Test
public void main() {
    try{
        //Try block contains code that may have exceptions.
        InputStream inputStream = new FileInputStream("a.txt");

        //If the try is finished and no exception occurs, then execute the finally block and the code after finally (if any).
        int i = 1/0;
        //If an exception occurs, try to match the catch block.
        throw new SQLException();
        //Using 1.8 JDK to catch multiple exceptions at the same time, runtimeException can also catch. Only the virtual machine cannot process after capture, so capture is not recommended.
    }catch(SQLException | IOException | ArrayIndexOutOfBoundsException exception){
        System.out.println(exception.getMessage());
        //Each catch block is used to catch and handle a specific exception, or subclass of this exception type. Multiple exceptions can be declared in a catch in Java 7.

        //The parentheses after catch define the exception type and exception parameters. If the exception matches and is the first one, the virtual machine will use this catch block to handle the exception.

        //In the catch block, you can use the exception parameter of this block to get the information about the exception. The exception parameter is a local variable in this catch block, which cannot be accessed by other blocks.

        //If the exception in the current try block is not caught in all subsequent catches, execute finally first, and then match the exception handler in the external caller of this function.

        //If no exception occurs in try, all catch blocks are ignored.

    }catch(Exception exception){
        System.out.println(exception.getMessage());
        //...
    }finally{
        //Finally blocks are usually optional.
        //Finally executes whether the exception occurs or not, whether the exception matches and is handled.

        //Finally, it mainly does some cleaning work, such as closing the flow, closing the database connection, etc.
    }

A try must have at least one catch or finally

try {
        int i = 1;
    }finally {
        //A try must have at least one catch block, otherwise, at least one finally block. But finally is not used to handle exceptions. Finally does not catch exceptions.
    }
}

When an exception occurs, the code behind the method does not run, even if the exception has been caught. Here is a strange example. Try catch finally again in catch

@Test
public void test() {
    try {
        throwE();
        System. Out. Println ("I threw an exception earlier");
        System. Out. Println ("I won't do it anymore");
    } catch (StringIndexOutOfBoundsException e) {
        System.out.println(e.getCause());
    }catch (Exception ex) {
    //Try catch finally can still be used in a catch block
        try {
            throw new Exception();
        }catch (Exception ee) {
            
        }finally {
            System. Out. Println ("my catch block has not been executed, and I will not execute it");
        }
    }
}
//Exceptions thrown in a method declaration must be handled by the calling method or continue to be thrown up,
//When throwing to JRE, the termination program cannot be processed
public void throwE (){
//        Socket socket = new Socket("127.0.0.1", 80);

        //When an exception is thrown manually, no error will be reported, but the method calling the method needs to handle the exception, otherwise an error will occur.
//        java.lang.StringIndexOutOfBoundsException
//At com.javase. Exception. Throw (exception handling. Java: 75)
//At com.javase. Exception. Exception handling method. Test (exception handling method. Java: 62)
        throw new StringIndexOutOfBoundsException();
    }

In fact, some languages can continue to run after encountering exceptions

In some programming languages, when an exception is handled, the control flow will recover to the exception throwing point and then execute. This strategy is called: recovery model of exception handling

In Java, the execution flow is restored to the catch block that handles the exception and then executed. This strategy is called: termination model of exception handling

“Irresponsible” throws

Throws is another way to handle exceptions, which is different from try Catch… Finally, throws simply declares the possible exceptions in the function to the caller, but does not handle them specifically.

The reason for this exception handling may be that the method itself does not know how to handle such an exception, or let the caller handle it better, and the caller needs to be responsible for the possible exception.

public void foo() throws ExceptionType1 , ExceptionType2 ,ExceptionTypeN
{ 
     //Exception objects of exceptiontype1, exceptiontype2, exceptiontypen or their subclasses can be thrown inside foo.
}

Tangled finally

Finally block, no matter whether the exception occurs or not, as long as the corresponding try is executed, it must also execute. There is only one way to keep a finally block from executing: system. Exit(). So finally block is usually used to release resources: close files, close database connections and so on.

A good programming habit is to open resources in the try block and clean up and release them in the finally block.

What should be noted:

1. Finally blocks do not have the ability to handle exceptions. Only catch blocks can handle exceptions.

2. In the same try Catch… In the finally block, if an exception is thrown in try and there is a matching catch block, execute the catch block first, and then execute the finally block. If there is no catch block match, perform finally first, and then go to the external caller to find the appropriate catch block.

3. In the same try Catch… In the finally block, if an exception occurs in try and an exception is thrown when handling the exception in the matching catch block, then the next finally block will execute: first execute the finally block, and then go to the peripheral callers to find the appropriate catch block.

Public class finally{
    public static void main(String[] args) {
        try {
            throw new IllegalAccessException();
        }catch (IllegalAccessException e) {
            // throw new Throwable();
            //If an exception is thrown again at this time, finally cannot be executed and only an error can be reported.
            //Finally, it will be executed at any time
            //Unless I show the call. Finally will not execute at this time
            System.exit(0);

        }finally {
            System. Out. Println ("calculate your ruthlessness");
        }
    }
}

Throw: a keyword used by JRE

throw exceptionObject

The programmer can also manually and explicitly throw an exception through the throw statement. The throw statement must be followed by an exception object.

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

public void save(User user)
{
      if(user  == null) 
          Throw new illegalargumentexception ("user object is empty");
      //......
 
}

Most of the following are excerpted from http://www.cnblogs.com/lulipro/p/7504267.html

This article is written in a very meticulous and admirable way. It is the most detailed article I have seen for it at present. It can be said that it stands on the shoulders of giants.

Exception call chain

Abnormal chaining

In some large, modular software development, once an exception occurs in a place, it will lead to a series of exceptions, just like the domino effect. Suppose that module B needs to call the method of module a to complete its own logic. If there is an exception in module a, then module B will fail to complete and an exception will occur.

==However, when B throws an exception, it will cover up the exception information of a, which will cause the source information of the exception to be lost. The chaining of exceptions can connect the exceptions of multiple modules in series, so that the exception information will not be lost. = =

Exception Chaining: construct a new exception object with an exception object as a parameter. The new object will contain information about the previous exception. This technology is mainly implemented by a function with throwable parameter of exception class. This is a parameter exception. We call it cause.

Looking at the throwable class source code, you can see that there is a throwable field cause, which saves the source exception parameters passed during construction. This design is the same as the node class design of the list, so it is natural to form a chain.

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;
    }
 
    //........
}

Let’s look at a real example of abnormal chain

Public class exception chain{
    @Test
    public void test() {
        C();
    }
    public void A () throws Exception {
        try {
            int i = 1;
            i = i / 0;
            //When I comment out this line of code and use method B to throw an error, the result is as follows
//April 27, 2018 10:12:30 PM org.junit.platform.launcher.core.serviceloadertestengineregistry loadtestengines
//Information: discovered testengines with IDS: [JUnit Jupiter]
//Java. Lang. error: B also made a mistake
//At com.javase. Exception. Exception chain. B (exception chain. Java: 33)
//At com.javase. Exception. Exception chain. C (exception chain. Java: 38)
//At com.javase. Exception. Exception chain. Test (exception chain. Java: 13)
//            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
//            Caused by: java.lang.Error
//At com.javase. Exception. Exception chain. B (exception chain. Java: 29)

        }catch (ArithmeticException e) {
            //Here, the lowest level exception is repackaged and thrown through the construction method of throwable class, at this time, the information of method a is injected. At last, when printing stack information, you can see the caused by
            Exception of method a.
            //If it is thrown directly, the stack information printing result can only see the error information of the upper method, but not the error of A.
            //So it needs to be packaged and thrown
            Throw new exception ("a method calculation error", e);
        }

    }
    public void B () throws Exception,Error {
        try {
            //Exception received from a,
            A();
            throw new Error();
        }catch (Exception e) {
            throw e;
        }catch (Error error) {
            Throw new error ("B also made a mistake", error);
        }
    }
    public void C () {
        try {
            B();
        }catch (Exception | Error e) {
            e.printStackTrace();
        }

    }

    //Final results
//Java.lang.exception: a method calculation error
//At com.javase. Exception. Exception chain. A (exception chain. Java: 18)
//At com.javase. Exception. Exception chain. B (exception chain. Java: 24)
//At com.javase. Exception. Exception chain. C (exception chain. Java: 31)
//At com.javase. Exception. Exception chain. Test (exception chain. Java: 11)
// ellipsis
//    Caused by: java.lang.ArithmeticException: / by zero
//At com.javase. Exception. Exception chain. A (exception chain. Java: 16)
//            ... 31 more
}

Custom exception

If you want to customize exception classes, you can extend exception classes. Therefore, such custom exceptions belong to checked exception. If you want to customize non checking exceptions, extend from runtimeException.

According to international conventions, custom exceptions should always contain the following constructors:

A parameterless constructor
A constructor with a string parameter and passed to the constructor of the parent class.
A string parameter and throwable parameter are passed to the parent constructor
A constructor with throwable parameter and passed to the constructor of the parent class.
The following is the complete source code of IOException class, which 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);
    }
}

Abnormal precautions

Abnormal precautions

When a subclass overrides a function with a throws declaration of its parent class, the exceptions declared by its throws declaration must be within the control of the parent class exception — the exception handler used to handle the throws method of the parent class, and must also be applicable to the throws method of the subclass. This is to support polymorphism.

For example, if the parent method throws has two exceptions, the child cannot throw three or more exceptions. If the parent class throws IOException, the child class must throw IOException or the child class of IOException.

As for why? I think, maybe the following example can illustrate.

class Father
{
    public void start() throws IOException
    {
        throw new IOException();
    }
}
 
class Son extends Father
{
    public void start() throws Exception
    {
        throw new SQLException();
    }
}

/**********************Suppose the above code is allowed (wrong in essence)***********************/

class Test
{
    public static void main(String[] args)
    {
        Father[] objs = new Father[2];
        objs[0] = new Father();
        objs[1] = new Son();
 
        for(Father obj:objs)
        {
        //Because the essence thrown by the son class is sqlexception, which cannot be handled by IOException.
        //So try here.. Catch cannot handle exceptions in son.
        //Polymorphism cannot be achieved.
            try {
                 obj.start();
            }catch(IOException)
            {
                 //Handle IOException
            }
         }
   }
}

==Java’s exception execution process is thread independent, and there is no impact between threads==

Java programs can be multithreaded. Each thread is an independent execution flow, independent function call stack. If the program has only one thread, an exception that is not handled by any code will cause the program to terminate. If it is multithreaded, an exception that is not handled by any code will only cause the thread where the exception is located to end.

In other words, exceptions in Java are thread independent. The problem of threads should be solved by the threads themselves, instead of being delegated to the outside, and will not directly affect the execution of other threads.

Here’s an example

Public class multithreaded exception{
    @Test
    public void test() {
        go();
    }
    public void go () {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0;i <= 2;i ++) {
            int finalI = i;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            executorService.execute(new Runnable() {
                @Override
                //The exception thrown by each thread will not affect the execution of other threads
                public void run() {
                    try {
                        System.out.println("start thread" + finalI);
                        throw new Exception();
                    }catch (Exception e) {
                        System.out.println("thread" + finalI + " go wrong");
                    }
                }
            });
        }
//Results:
//        start thread0
//        thread0 go wrong
//        start thread1
//        thread1 go wrong
//        start thread2
//        thread2 go wrong
    }
}

When finally meets return

First, a fact that is not easy to understand:

In the try block, even if there are return, break, continue and other statements that change the execution flow, finally will execute.

public static void main(String[] args)
{
    int re = bar();
    System.out.println(re);
}
private static int bar() 
{
    try{
        return 5;
    } finally{
        System.out.println("finally");
    }
}
/ * output:
finally
*/

Many people are always summing up the order and law of execution when facing this problem, but I think it is still difficult to understand. I summed up a method myself. Use the following GIF chart to illustrate.

[failed to transfer pictures from the external chain (img-scef4t85-1569073569354) (http://incdn1.b0.upaiyun.com/2017/09/0471c2805ebd5a463211ced478eaf7f8. GIF))

That is to say, try Catch… As long as the return in finally can be executed, it will be executed. They write the return value to the same memory address (assuming the address is 0 × 80). The data executed later will cover the data executed first, and the return value obtained by the caller is the last one written. Then, according to this idea, the following example is not difficult to understand.

Return in finally overrides the return value in try or catch.

public static void main(String[] args)
    {
        int result;
 
        result  =  foo();
        System.out.println(result);     /////////2
 
        result = bar();
        System.out.println(result);    /////////2
    }
 
    @SuppressWarnings("finally")
    public static int foo()
    {
        trz{
            int a = 5 / 0;
        } catch (Exception e){
            return 1;
        } finally{
            return 2;
        }
 
    }
 
    @SuppressWarnings("finally")
    public static int bar()
    {
        try {
            return 1;
        }finally {
            return 2;
        }
    }

Return in finally suppresses (destroys) the exception in the previous try or catch block

class TestException
{
    public static void main(String[] args)
    {
        int result;
        try{
            result = foo();
            System. Out. Println (result); // output 100
        } catch (Exception e){
            System. Out. Println (e.getmessage()); // no exception caught
        }
 
        try{
            result  = bar();
            System. Out. Println (result); // output 100
        } catch (Exception e){
            System. Out. Println (e.getmessage()); // no exception caught
        }
    }
 
    //Exception suppressed in catch
    @SuppressWarnings("finally")
    public static int foo() throws Exception
    {
        try {
            int a = 5/0;
            return 1;
        }catch(ArithmeticException amExp) {
            Throw new exception ("I will be ignored because return is used in finally below");
        }finally {
            return 100;
        }
    }
 
    //Exceptions in try are suppressed
    @SuppressWarnings("finally")
    public static int bar() throws Exception
    {
        try {
            int a = 5/0;
            return 1;
        }finally {
            return 100;
        }
    }
}

The exception in finally will overwrite (destroy) the exception in the previous try or catch

class TestException
{
    public static void main(String[] args)
    {
        int result;
        try{
            result = foo();
        } catch (Exception e){
            System. Out. Println (e.getmessage()); // output: I am exception in final
        }
 
        try{
            result  = bar();
        } catch (Exception e){
            System. Out. Println (e.getmessage()); // output: I am exception in final
        }
    }
 
    //Exception suppressed in catch
    @SuppressWarnings("finally")
    public static int foo() throws Exception
    {
        try {
            int a = 5/0;
            return 1;
        }catch(ArithmeticException amExp) {
            Throw new exception ("I'll be ignored because a new exception is thrown in finally below");
        }finally {
            Throw new exception ("I'm an exception in finally");
        }
    }
 
    //Exceptions in try are suppressed
    @SuppressWarnings("finally")
    public static int bar() throws Exception
    {
        try {
            int a = 5/0;
            return 1;
        }finally {
            Throw new exception ("I'm an exception in finally");
        }
 
    }
}

The above three examples are different from ordinary people’s coding thinking, so I suggest:

Do not use return in fill.

Do not throw an exception in finally.

Lighten the task of finally. Don’t do anything else in finally. It’s most appropriate that finally block is only used to release resources.

Try to write all return at the end of the function instead of try Catch… Finally.

Java abnormal common interview questions

Here is my personal summary of the knowledge about exception and error that Java and J2EE developers are often asked in interviews. When sharing my answers, I also made quick revisions to these questions and provided source code for in-depth understanding. I summarized all kinds of difficult problems, suitable for novice code farmers and advanced Java code farmers. If you encounter a problem that I don’t have in my list, and this problem is very good, please share it in the comments below. You can also share in the comments about your interview mistakes.

1) What is exception in Java?
This question is often asked for the first time when it comes to exceptions or when interviewing rookies. I’ve never met a senior or senior engineer who asked about this, but I’m very willing to ask about it for novices. In short, exceptions are the way Java communicates system and program errors to you. In Java, exception functions are implemented through classes such as throwable, exception and runtimeException, and then there are keywords for handling exceptions, such as throw, throws, try, catch and finally. All exceptions are derived from throwable. Throwable further divides errors into java.lang.exception
And java.lang.error. Java.lang.error are used to handle system errors, such as java.lang.stackoverflowerror. Exception is then used to handle program errors, requested resources are not available, and so on.

2) What’s the difference between checked and unchecked exceptions in Java?

This is a very popular Java exception interview question, which will appear in various levels of Java interview. The main difference between checking and non checking exceptions lies in the way they are handled. Check exceptions need to be handled at compile time with try, catch and finally keywords, otherwise the compiler will report an error. This is not necessary for non checking exceptions. In Java, all exceptions inherited from the java.lang.exception class are check exceptions, and all exceptions inherited from the runtimeException are called non check exceptions.

3) What are the similarities between NullPointerException and arrayindexoutofboundexeption in Java?

This is not a very popular problem in Java exception interview, but it will appear in different levels of novice interview to test whether the candidates are familiar with the concepts of check exception and non check exception. By the way, the answer to this question is that both of these exceptions are non checking exceptions and inherit from runtimeException. This problem may lead to another problem, that is, what is the difference between Java and C arrays, because there is no size limit for the arrays in C, and arrayindexoutofboundexception will never be thrown.

4) What are the best practices you follow in Java exception handling?

This question is very common in interviewing technical managers. Because exception handling is very important in project design, it is necessary to master exception handling. There are many best practices for exception handling, which are listed below to improve the robustness and flexibility of your code:

1) The Boolean value is returned instead of null when the method is called, which can be NullPointerException. Because null pointer is the most disgusting exception in Java

2) Don’t leave the code in the catch block. An empty catch block is an error event in exception handling because it just catches the exception without any handling or prompting. Usually you should at least print out the abnormal information, of course, you’d better deal with the abnormal information according to your needs.

3) If you can throw a checked exception, try not to throw a checked exception. By removing duplicate exception handling code, the readability of the code can be improved.

4) Never let your database related exceptions appear to the client. Because most database and sqlexception exceptions are controlled exceptions, in Java, you should handle the exception information in Dao layer, and then return the handled exception information that can be understood by users and corrected according to the exception prompt information.

5) in Java, we must call the close () method in the finally block after database connection, database query and stream processing.

5) Since we can use runtimeException to handle errors, why do you think there are check exceptions in Java?

This is a controversial question and you should be careful when answering it. Although they would like to hear your opinion, they are most interested in persuasive reasons. I think one of the reasons is that the existence of checking exceptions is a design decision, influenced by experience in programming languages such as C + + that are older than Java. The vast majority of checked exceptions are in the Java. IO package, which makes sense, because when you request a non-existent system resource, a strong program must be able to handle this situation gracefully. By declaring IOException as a check exception, Java ensures that you can handle exceptions gracefully. Another possible reason is to use catch or finally to ensure that a limited number of system resources (such as file descriptors) are released as early as possible after you use them. Joshua
This topic is involved in several parts of the effective java book written by Bloch, which is worth reading.

6) What’s the difference between throw and throws in Java?

An interview question that a JAVA beginner should master. Throw and throws look very similar at first glance, especially when you are a JAVA beginner. Although they look similar, they are used to handle exceptions. But in the code, the use method and the place are different. Throws always appear in a function header to indicate various exceptions that may be thrown by the member function. You can also declare unchecked exceptions, but this is not enforced by the compiler. If the method throws an exception, you need to handle the exception when calling the method. Another keyword, throw, is used to throw any exception. According to the syntax, you can throw any throwable (i.e. throwable
Throw can interrupt program operation, so it can be used instead of return. The most common example is to throw unsupported operationexception code in an empty method where return is required as follows:

123 private``static void show() {``throw``new UnsupportedOperationException(``"Notyet implemented"``);``}

You can see more differences between these two keywords in Java in this article.

7) What is “abnormal chain”?

“Exception chain” is a very popular concept of exception handling in Java. It means that an exception is thrown when an exception is handled, resulting in an exception chain. This technology is mostly used to encapsulate checked exception into unchecked exception or runtimeException. By the way, if you decide to throw a new exception because of the exception, you must include the original exception, so that the handler can access the final source of the exception through the getcause() and initcause() methods.

)Have you ever custom implemented exceptions? How do you write it?

Obviously, most of us have written custom or business exceptions, such as accountnotfoundexception. The main reason to ask about this Java exception during the interview is to find out how you use this feature. This can handle exceptions more accurately and delicately. Of course, it is closely related to whether you choose checked or unchecked exception. By creating a specific exception for each specific situation, you provide a better choice for the caller to handle the exception better. I prefer more precise exceptions than general exceptions. Creating a large number of custom exceptions will increase the number of project classes, so maintaining a balance between custom exceptions and general exceptions is the key to success.

9) What changes have been made to exception handling in JDK7?

This is a new Java exception handling interview question. There are two new features for error and exception handling in JDK7. One is that multiple exceptions can be generated in one catch block, just like multiple catch blocks. The other is automated resource management (ARM), also known as the try with resource block. These two features can reduce the amount of code and improve the readability of code when handling exceptions. Understanding these features will not only help developers write better exception handling code, but also make you more prominent in the interview. I recommend you read the Java 7 introduction, so that you can have a deeper understanding of these two very useful features.

10) Have you ever encountered outofmemoryerror? How did you handle it?

This interview question will be used when interviewing senior programmers. The interviewer wants to know how you deal with this dangerous outofmemoryerror. It must be admitted that no matter what project you do, you will encounter this problem. So if you say you haven’t, the interviewer won’t buy it. If you are not familiar with this problem, or even have not encountered it, and you have 3 or 4 years of Java experience, then be ready to deal with it. While answering this question, you can also take the opportunity to show off your awesome skills in dealing with memory leaks, tuning, and debugging. I find that people who master these skills can make a deep impression on the interviewer.

11) If the method returns the result before executing the finally block, or the JVM exits, will the code in the finally block still execute?

This question can also be asked in another way: “if you call System.exit () in try or finally, what will the result be?” Knowing how to execute a finally block, even if you have used return to return results in try, is very valuable for understanding Java exception handling. The code in the finally block will not execute only if there is system. Exit (0) in try to exit the JVM.

12) The difference of final, finalize and finally keywords in Java

This is a classic java interview question. A friend of mine asked this question when he recruited core Java developers for Morgan Stanley in telecommunications. Final and finally are Java keywords, while finalize is the method. The final keyword is very useful when creating immutable classes, except to declare that the class is final. The finalize () method is the garbage collector calling before recovering an object, but there is no guarantee that this method will be called in the Java specification. Finally keyword is only keyword related to exception handling discussed in this article. In your product code, you must use the finally block when closing the connection and resource files.

Reference articles

https://www.xuebuyuan.com/3248044.html
https://www.jianshu.com/p/49d2c3975c56
http://c.biancheng.net/view/1038.html
https://blog.csdn.net/Lisiluan/article/details/88745820
https://blog.csdn.net/michaelgo/article/details/82790253

WeChat official account

Java technology

If you want to pay attention to my updated articles and dry cargo, you can pay attention to my official account, Java technology, a technical station of Ali Java engineer, author Huang Xiaoxie, focusing on Java Related technologies: SSM, springboot, mysql, distributed, middleware, cluster, Linux, network, multithreading, occasionally talking about docker and elk, but also sharing technology dry goods and learning experience, committed to Java full stack development!

Necessary learning resources for Java Engineers:Some Java engineers often learn resources, pay attention to the official account, and respond to the background keywords.“Java”You can get it for free.

我的公众号

Official account number: Huang Xiaoxie

The author is a 985 master, ant financial JAVA engineer, focusing on the JAVA back-end technology stack: SpringBoot, MySQL, distributed, middleware, microservices, but also understand the investment and financial management, occasionally speak about the algorithm and computer theoretical basis, adhere to learning and writing, believe in the power of lifelong learning!

Programmer 3T technology learning resources:Some programmers learn the resources of the technology package, after the official account, the background reply key words.“Information”You can get it for free.

Solid Java Foundation Series 10: deep understanding of Java exception system