current position:Home>How to handle Java exceptions?

How to handle Java exceptions?

2022-05-15 05:19:54InfoQ

Java Exception class hierarchy ?

  • Throwable
      yes  Java  A superclass of all errors and exceptions in a language .
  • Error
      Classes and subclasses : An error in a program that cannot be handled , Indicates that a serious error has occurred in the running application .
  • Exception
      Exceptions that can be caught and handled by the program itself .Exception  There are two types of anomalies : Runtime and compile time exceptions .

null
  • Runtime exception
All are RuntimeException Class and its subclass exception , Such as NullPointerException( Null pointer exception )、IndexOutOfBoundsException( Subscript out of range exception ) etc. , These exceptions are not checked , The program can choose to capture the processing , Or not . These exceptions are usually caused by program logic errors , Programs should try to avoid such exceptions from a logical point of view .
Runtime exceptions are characterized by Java The compiler will not check it , in other words , When this kind of exception may appear in the program , Even if it doesn't work try-catch Statement capture it , It doesn't work throws The clause declares to throw it , Will also compile through .
  • Non runtime exception
     ( Compile exception )
yes RuntimeException An exception , They all belong to Exception Classes and subclasses . From the perspective of program syntax, it is an exception that must be handled , If you don't deal with , The program can't be compiled . Such as IOException、SQLException And user-defined Exception abnormal , In general, no custom check exception .

Detectable anomalies (checked exceptions) And undetectable anomalies (unchecked exceptions) difference ?

  • We can find out the abnormality
    ( Exceptions that the compiler requires to handle ):
The right program is running , It's easy to see 、 An abnormal condition that can be tolerated by reason . It can be found that the abnormality is abnormal , But to a certain extent, its occurrence can be predicted , And once that happens , We have to deal with it in some way .
except RuntimeException And its subclasses , Other Exception Class and its subclasses are queryable exceptions . This anomaly is characterized by Java The compiler will check it , in other words , When this kind of exception may appear in the program , Either use try-catch Statement capture it , Either use throws The clause declares to throw it , Otherwise the compilation will not pass .
  • No exceptions can be found
    ( Compiler does not require mandatory exceptions )
Including runtime exceptions (RuntimeException And its subclasses ) And mistakes (Error).

throw and throws The difference between ?

  • Abnormal declaration (throws)
stay Java in , The currently executed statement must belong to a method ,Java Interpreter call main Method execution starts the execution of the program . If there is a check exception in the method , If you don't capture it , The exception must be explicitly declared in the method header , In order to inform the method caller that this method has an exception , Need to be dealt with .  In a method declaration , Keyword used in method header throws, Followed by the exception to declare . If you declare multiple exceptions , Use commas to separate . As shown below :
public static void method() throws IOException, FileNotFoundException{
 //something statements
}
  • Throw exception (throw)
If the code may cause some kind of error , You can create a suitable exception class instance and throw it , This is throwing an exception . As shown below :
public static double method(int value) {
 if(value == 0) {
 throw new ArithmeticException(" Parameter cannot be 0"); // Throw a runtime exception
 }
 return 5.0 / value;
}

Java 7  Of  try-with-resource?

If your resources are realized  AutoCloseable  Interface , You can use this grammar . Most of the  Java  Standard resources all inherit this interface . When you are in  try  Open resource in clause , Resources will be in  try  Close automatically after code block execution or exception handling .
public void automaticallyCloseResource() {
 File file = new File("./tmp.txt");
 try (FileInputStream inputStream = new FileInputStream(file);) {
 // use the inputStream to read a file
 } catch (FileNotFoundException e) {
 log.error(e);
 } catch (IOException e) {
 log.error(e);
 }
}

Bottom layer of exception ?

mention JVM Mechanism for handling exceptions , You need to mention Exception Table, Hereinafter referred to as exception table . We are not in a hurry to introduce the exception table , Let's start with a simple  Java  A small example of handling exceptions .
public static void simpleTryCatch() {
 try {
 testNPE();
 } catch (Exception e) {
 e.printStackTrace();
 }
}
Use javap To analyze this code ( You need to use it first javac compile )
//javap -c Main
 public static void simpleTryCatch();
 Code:
 0: invokestatic #3 // Method testNPE:()V
 3: goto 11
 6: astore_0
 7: aload_0
 8: invokevirtual #5 // Method java/lang/Exception.printStackTrace:()V
 11: return
 Exception table:
 from to target type
 0 3 6 Class java/lang/Exception
See the code above , There should be a knowing smile , Because I finally saw Exception table, That is, the exception table we want to study .
The exception table contains one or more exception handlers (Exception Handler) Information about , This information includes the following
  • from
      The starting point of possible exceptions
  • to
      The end point where exceptions may occur
  • target
      Above from and to The location of the exception handler after the previous exception
  • type
      The class information of the exception handled by the exception handler

If you reprint , Please indicate the source : Open source byte    https://sourcebyte.cn/article/122.html

copyright notice
author[InfoQ],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/131/202205111232226684.html

Random recommended