Problems related to anomalies in Java have always been a frequent topic in the interview. Although it is a relatively basic knowledge point, there are still a lot of goods in the process of sorting out, reviewing the old and learning the new. Hope can also bring some help to you.

What is an exception?

All errors that cause our program to terminate prematurely, or do not execute in the desired direction, are collectively called exceptions.

Classification of anomalies

All exceptions are inherited from Throwable, that is, ** exceptions and errors are inherited from Throwable. **

Note: In Java, only instances of Throwable types can be thrown or caught (try.. Catch)

Error

An Error is an Error that is unlikely to occur under normal circumstances and has nothing to do with how the code is written. Usually represents a problem with the JVM at runtime, such as an internal system error or insufficient resources.

Common ones are: OutOfMemoryError (memory overflow), VirtualMachineError (VirtualMachineError), NoClassDefFoundError (class definition error)

Exception

Exceptions are errors that can be expected when a program is running. Exceptions fall into two categories

  • Checkable exceptions

    We must carry out explicit capture processing in the program, otherwise it will compile errors, such as IOException, SQLException

The following is a method to read the file line by line. If no exception is handled, an error is reported during compilation.

try {
        Thread.sleep(10);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
Copy the code
public static void readFile(String fileName) {
        File file = new File(fileName);
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            int line = 1;
            // Read by line
            while(br.readLine() ! =null) { System.out.println(br.readLine()); line++; }}catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(br ! =null) {
                try {
                    br.close();
                } catch(IOException e) { e.printStackTrace(); }}}}Copy the code
  • Uncheckable exception:

    Common have a NullPointerException (null pointer), ArrayIndexOutOfBoundException (subscript cross-border exception). Whether or not to capture, the program itself does not require us to do this. But you can avoid logic errors in your code during execution.

As follows, extracting elements from the collection itself does not require exception catching, but NullPointerException is raised at runtime

List<String> lst = Arrays.asList("A"."B"."C");
String str = lst.get(3);
Copy the code

Note:

According to ali Java development manual, runtimeExceptions that can be pre-detected should not be handled by catch method. Such as NullPointExceotion. You can start with non-controlling judgments, such as if(obj! = null){… }

What’s the difference between Exception and Error? Of course, exception handling is often referred to as a killer call during an interview. To further answer the above question, I found a picture on the Internet.

Exception handling

Exception handling in the code focuses on checkable exceptions. ,

By the try… Catch statement

try {
    // The code to capture
} catch (Exception e1) {
    // Catch code block
}
finally {
    // A block of code that executes regardless of whether an exception occurs
}
Copy the code

When an exception occurs in a try block, a catch block is executed. Eventually, however, a block of code in Finally must be executed, for example to do some recycling.

Throws the exception to the upper layer for processing

  • throws

    Used to declare all exceptions that a method may or may not generate, passing them up to the caller without doing anything.

    After a method declaration, multiple exceptions are separated by commas.

    public String getValue(List list,int num) throws Exception{
        return (String) list.get(num);
    }
    Copy the code
  • throw

    To throw a specific exception type

    Just throw an exception object, inside the method body. An exception must be thrown.

    public static void main(String[] args) {
        try {
            throwNumException(11);
        } catch(Exception e) { System.out.println(e.getMessage()); }}public static void throwNumException(int a) throws Exception{
        if (a > 10) {
            throw new Exception("The value of A does not meet the requirements."); }}Copy the code

    Precautions for exception handling

    1. Use exception handling with caution

    try.. A catch can cause additional overhead, so it is recommended that you only catch critical code and never wrap a large block of code in a try.

    Every time Java instantiates an Exception, it takes a snapshot of the stack at that time. If operations are frequent, the cost of resources cannot be ignored.

    2. Clean up the resource in the finally code block

    The following code executes normally without any problems, but if an exception occurs before shutting down the resource, the resource cannot be released.

    File file = new File(fileName);
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            // ignore logical processing
            br.close(); // Close the resource
        } catch (IOException e) {
            e.printStackTrace();
        }
    Copy the code

    Correct way to write:

    try {
            br = new BufferedReader(new FileReader(file));
            // ignore logical processing
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(br ! =null) {
                try {
                    br.close();
                } catch(IOException e) { e.printStackTrace(); }}}Copy the code

    3. Specify specific exceptions

    The following code does not have a problem executing, but it catches a generic Exception, which should be properly written to catch specific exceptions.

    Thread.sleep() throws InterruptedException.

    try {
        Thread.sleep(10);
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    Copy the code

    In daily development, we often need to be more intuitive to observe exceptions. If multiple exceptions are thrown, use common exceptions to catch them, so that it is easy to locate the problem. A more rigorous version would look like this

    try {
        // ignore the logical code
        Thread.sleep(10);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    Copy the code

    ** (the following points are extracted from the Taishan version of Ali development manual, you can reply to [Ali] in the background of the public account “Java column”) to obtain **

    4, do not use abnormal process control, condition control

    The original intention of exception design is to solve all kinds of unexpected situations in program operation, and the efficiency of exception processing is much lower than that of condition judgment

    5. Distinguish stable code from unstable code when catching

    Stable code refers to the code that will not fail again no matter if it is not stable. When catching unstable code, try to distinguish the exception type and then handle the corresponding exception.

    6. Capture is about processing

    Catch an exception to handle it, don’t catch it and throw it away without doing anything. If you don’t want to handle it, throw the exception to its caller. The outermost business consumer must handle the exception and turn it into something that the user can understand.

The interview

Which one should be used first, finally or return in try?

Let’s start with a few examples

1.

   public static int getNum(a) {
        int a = 10;
          try {
              System.out.println("Enter a try");
              return a;
          } catch (Exception e) {
              e.printStackTrace();
              return a;
          }
          finally {
              a = 20;
              System.out.println("The value of a is:+ a); }}Copy the code

Execution Result:

The values that enter try A are :20, 10Copy the code

Conclusion: You can see that after entering the try, the finally block of code is executed before the return

2,

public static void main(String[] args) {
        System.out.println(getNum());

    }

public static int getNum(a) {
    int a = 10;
    try {
        System.out.println("Perform a try");
        //ignore
        System.out.println("The return");
        return a;
    } catch (Exception e) {
        e.printStackTrace();
        return a;
    }
    finally {
        System.out.println(Start executing finally);
        a = 20;
        System.out.println("Execute finally end"); }}Copy the code

Running results:

Execute try is about toreturnStart Run finally. Run finally. End 10Copy the code

The result prints 10, as if the change to a in finally didn’t work. This is stated in the JVM specification

If the try clause executes a return, the compiled code does the following:
1. Saves the return value (if any) in a local variable.
2. Executes a jsr to the code for the finally clause.
3. Upon return from the finally clause, returns the value saved in the local variable.

Copy the code

In the case of a return in a try, the value of the try to return is stored in a local variable, i.e. x=10 in the above example is saved. We then execute the finally statement, which returns the value that exists in the local variable, that is, x=10.

3,

public static int getNum(a) {
        int a = 10;
        try {
            return a;
        } catch (Exception e) {
            e.printStackTrace();
            return a;
        }
        finally {
            a = 20;
            returna; }}Copy the code

Execution Result:

20

Copy the code

Conclusion: If finally has a return, the return in the try is ignored

Note: The Ali development manual states that you should never use return in finally

Conclusion:

  • A return ina try will hold the value, and whatever is done to the value in the finally statement will return the value held in the try statement.
  • When both try and finally statements have return statements, the return in the try is ignored.

At the end of the article’s welfare

Liver the whole network, 43 Copies of Java mind map, need to take!! !

Java Interview Manual V1.0, free in hd PDF