Talk about the abnormal mechanism of Java

Share this article from Huawei cloud community "Java exception mechanism featured knowledge of the problem," the original author: breakDraw.

Java exception refers to some errors that may occur when the program is running, such as: file not found, network connection failure, illegal parameters, etc. An exception is an event that occurs during the running of a program and interrupts the normal instruction flow of the program being executed.

Java describes various exceptions through many subclasses of the Throwable class in the API. Therefore, Java exceptions are all objects, instances of Throwable subclasses that describe error conditions that appear in a piece of code. When the condition is generated, the error will raise an exception. For runtime exceptions, errors, or checkable exceptions, the exception handling methods required by Java technology are different.

Abnormal system classification

Q: The relationship between Throwable and Error
A: Throwable is the base class of Error, and it is also the base class of Exception.
A good picture. You can see common exceptions and errors .

Q: The relationship between Error and Exception
A:

  • Errors are generally errors that directly cause jvm errors, such as Java virtual machine running errors, etc. If the current thread appears, it will not continue to run.
  • Excpetion is an exception that can be handled by the program itself. After it happens, it can still operate normally.

Q: Can Error be caught by catch?
A: As long as it is Throwable and its subclasses, it can throw and catch. But it is not recommended to catch Error.

The exception system can also be divided into these two categories:

  • Unchecked exception (non-checked exception)
    is also called runtime exception (RuntimeException), such as common NullPointerException, IndexOutOfBoundsException. For runtime exceptions, the java compiler does not require exception capture processing or throwing declarations, and it is up to the programmer to decide.
  • Checked exceptions (checked exceptions, compiled exceptions)
    are also called non-runtime exceptions (exceptions other than runtime exceptions are non-runtime exceptions). The java compiler forces programmers to capture processing, such as common IOExeption and SQLException. For non-runtime exceptions, if you do not capture or throw declaration processing, the compilation will not pass.

Exception catch and return

Q: Return-finally trap 1: Can finally update the variable value of return by modifying the variable?

int f() {
  int a = 1;
  try {
      return a;
  }
  finally {
      a=2;
  }
}

A: No, f returns 1.

Q: Return-finally trap 2: When there is a return in the finally, which one is returned?

int f() {
  try {
      return 1;
  }
  finally {
      return 2;
  }
}

A: Return to finally, return 2.

Q: Under what circumstances can the steps in the finally block not be executed?
A: Only by calling System.exit(0) to exit jvm before finally can finally not be executed.

Q: What will happen next?

try {
    start();
} catch (Exception ex) {
    System.out.println("catch Exception");
} catch (RuntimeException re) {
    System.out.println("catch RuntimeException");
}

A: It is an error to compile directly. The catch will be in order, and if one match is matched, no further matches will be made. Therefore, the compiler recognizes that RuntimeExcpetion will never be caught, and reports an error in advance.

Q: When throwing an exception, do return in finally, then will the exception be thrown?

static int f() {
    try {
        int a = 1/0;
        return a;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        return -1;
    }
}
public static void main(String[] args) {
    System.out.println(f());
}

A: No, return -1.

That is, doing return in final will interrupt throw,
so never do return operations in finally

Issues related to checked exceptions

Q: When a subclass overrides a base class method, can it throw exceptions that do not exist in the base class method?
Like the following:

class A{
    void f() throws IOException{
    }
}
class B extends A{
    void f() throws IOException, SQLException {
    }
}

A: No, just compile directly and report an error. That is, when the subclass overwrites the superclass method, the exception following the throws keyword must be less than or equal to the superclass method exception.

Q: When the close of a resource is called in finally, a checked exception will also be thrown. Besides doing try-catch in finally, what else can be done?

Like the following, finally has a catch, which is ugly:

TryWithResource tryWithResource = new TryWithResource();
        try {
            System.out.println(tryWithResource.age);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                tryWithResource.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

A: If it is JDK1.7, you can use try-with-resource syntax.

The resource class needs to implement the AutoCloseable interface and follow the creation of the resource after the try brackets when trying, as follows:

    public static void main(String[] args) {
        try (TryWithResource tryWithResource = new TryWithResource()) {
            System.out.println(tryWithResource.age);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

So there is no need to write finally, finally+close will be automatically added to us by the compiler.

Q: How to catch an exception if a thread throws it?

A: Implement exception handling interface MyUnchecckedExceptionhandler

public class MyUnchecckedExceptionhandler implements UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("捕获异常处理方法:" + e);
    }
}

Then set the implementation class to the corresponding thread.

Thread t = new Thread(new ExceptionThread());
t.setUncaughtExceptionHandler(new MyUnchecckedExceptionhandler());
t.start();

 

Click to follow and learn about Huawei Cloud's fresh technology for the first time~

Guess you like

Origin blog.csdn.net/devcloud/article/details/115321108