Home >Java >javaTutorial >Java exception introduction and specific code of the architecture

Java exception introduction and specific code of the architecture

黄舟
黄舟Original
2017-06-18 09:43:021314browse

This article mainly shares the introduction and architecture of Java exceptions, which has certain reference value. Interested friends can refer to it

Introduction to Java exceptions

Java exceptions are a consistent mechanism provided by Java to identify and respond to errors.

The Java exception mechanism can separate the exception handling code in the program from the normal business code, ensuring that the program code is more elegant and improving the robustness of the program. When exceptions are used effectively, exceptions can clearly answer the three questions what, where, why: the exception type answers "what" was thrown, and the exception stack trace answers "where" it was thrown. Out, the exception message answers "why" it is thrown.
Several keywords used in the Java exception mechanism: try, catch, finally, throw, throws.
•try  -- used for monitoring. Place the code to be monitored (the code that may throw an exception) within the try statement block. When an exception occurs within the try statement block, the exception will be thrown.
•catch -- used to catch exceptions. catch is used to catch exceptions that occur in the try statement block.
• finally -- The finally statement block will always be executed. It is mainly used to recycle physical resources (such as database connections, network connections, and disk files) opened in try blocks. Only the finally block, after execution is completed, will come back to execute the return or throw statement in the try or catch block. If a statement such as return or throw is used in the finally block, it will not jump back to execution and stop directly.
• throw -- used to throw exceptions.
• throws -- used in method signatures to declare exceptions that may be thrown by the method.

The following is a brief understanding of these keywords through several examples.

Example 1: Understand the basic usage of try and catch


public class Demo1 {

  public static void main(String[] args) {
    try {
      int i = 10/0;
       System.out.println("i="+i); 
    } catch (ArithmeticException e) {
       System.out.println("Caught Exception"); 
      System.out.println("e.getMessage(): " + e.getMessage()); 
      System.out.println("e.toString(): " + e.toString()); 
      System.out.println("e.printStackTrace():");
      e.printStackTrace(); 
    }
  }
}

Running results:

Caught Exception
e.getMessage(): / by zero
e.toString(): java.lang.ArithmeticException: / by zero
e.printStackTrace():
java .lang.ArithmeticException: / by zero
at Demo1.main(Demo1.java:6)

Result description: There is an operation of dividing by 0 in the try statement block. The operation will throw java.lang.ArithmeticException. Catch the exception through catch.

Observing the results, we found that System.out.println("i="+i) was not executed. This shows that after an exception occurs in the try statement block, the remaining content in the try statement block will no longer be executed.

Example 2: Understand the basic usage of finally
Based on "Example 1", we add the finally statement.


public class Demo2 {

  public static void main(String[] args) {
    try {
      int i = 10/0;
       System.out.println("i="+i); 
    } catch (ArithmeticException e) {
       System.out.println("Caught Exception"); 
      System.out.println("e.getMessage(): " + e.getMessage()); 
      System.out.println("e.toString(): " + e.toString()); 
      System.out.println("e.printStackTrace():");
      e.printStackTrace(); 
    } finally {
      System.out.println("run finally");
    }
  }
}

Run result:

Caught Exception
e.getMessage(): / by zero
e.toString() : java.lang.ArithmeticException: / by zero
e.printStackTrace():
java.lang.ArithmeticException: / by zero
at Demo2.main(Demo2.java:6)
run finally

Result description: The finally statement block is finally executed.

Example 3: Understand the basic usage of throws and throw
throws is used to declare thrown exceptions, and throw is used to throw exceptions.


class MyException extends Exception {
  public MyException() {}
  public MyException(String msg) {
    super(msg);
  }
}

public class Demo3 {

  public static void main(String[] args) {
    try {
      test();
    } catch (MyException e) {
      System.out.println("Catch My Exception");
      e.printStackTrace();
    }
  }
  public static void test() throws MyException{
    try {
      int i = 10/0;
       System.out.println("i="+i); 
    } catch (ArithmeticException e) {
      throw new MyException("This is MyException"); 
    }
  }
}

Run result:

Catch My Exception
MyException: This is MyException
at Demo3.test( Demo3.java:24)
at Demo3.main(Demo3.java:13)

Result description:

MyException is inherited from Exception Subclass. An ArithmeticException exception (divisor is 0) is generated in the try statement block of test(), and the exception is captured in catch; then a MyException exception is thrown. The main() method captures the MyException thrown in test().

Java exception framework

Java exception architecture diagram

1. Throwable

Throwable is the super class of all errors or exceptions in the Java language.
Throwable contains two subclasses: Error and Exception. They are often used to indicate that something unusual has occurred.
Throwable contains a snapshot of the thread execution stack when its thread is created. It provides interfaces such as printStackTrace() to obtain stack trace data and other information.

2. Exception

Exception and its subclasses are a form of Throwable, which points out reasonable The conditions that the application wants to capture.

3. RuntimeException

RuntimeException is the superclass of exceptions that may be thrown during normal operation of the Java virtual machine.
The compiler will not check RuntimeException. For example, when the divisor is zero, an ArithmeticException is thrown. RuntimeException is the superclass of ArithmeticException. When the code divides by zero, it can still be compiled if it neither "throws an ArithmeticException through the throws declaration" nor "handles the exception through try...catch...". This is what we mean by "the compiler does not check for RuntimeException"!
If the code will generate a RuntimeException, you need to modify the code to avoid it. For example, if division by zero occurs, you need to avoid this through code!

4. Error

Like Exception, Error is also a subclass of Throwable. It is used to indicate serious problems that reasonable applications should not attempt to catch; most such errors are exceptional conditions.
Like RuntimeException, the compiler will not check for Error.

Java divides throwable structures into three types: Checked Exception, RuntimeException and Error.

(01) Runtime exception

Definition: RuntimeException and its subclasses are called runtime exceptions.
Features: Java compiler will not check it. In other words, when this kind of exception may occur in the program, if it is neither thrown through the throws statement nor caught with a try-catch statement, it will still be compiled. For example, ArithmeticException generated when the divisor is zero, IndexOutOfBoundsException generated when the array exceeds the bounds, ConcurrentModificationException generated by the fail-fail mechanism, etc., are all runtime exceptions.
Although the Java compiler does not check runtime exceptions, we can also declare a throw through throws, or catch it through try-catch.
If a runtime exception occurs, it needs to be avoided by modifying the code. For example, if division by zero occurs, you need to avoid this through code!

(02) Checked exception

Definition: Exception class itself, and other subclasses of Exception subclasses except "runtime exception" It is a checked exception.
Features: Java compiler will check it. Such exceptions must either be declared and thrown through throws, or caught and processed through try-catch, otherwise they cannot pass compilation. For example, CloneNotSupportedException is a checked exception. When an object is cloned through the clone() interface, and the class corresponding to the object does not implement the Cloneable interface, a CloneNotSupportedException exception will be thrown.
Checked exceptions are usually recoverable.

(03) Error

Definition: Error class and its subclasses.
Features: Like runtime exceptions, the compiler will not check for errors.
When resources are insufficient, constraints fail, or other conditions occur that prevent the program from continuing to run, an error occurs. The program itself cannot fix these errors. For example, VirtualMachineError is an error.
According to Java convention, we should not implement any new Error subclasses!
For the above three structures, which one should we use when throwing an exception or error? The advice given in "Effective Java" is to use checked exceptions for recoverable conditions and runtime exceptions for program errors.

The above is the detailed content of Java exception introduction and specific code of the architecture. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn