Java exception handling try... The catch... The use of advanced statements

  • 2020-04-01 04:24:43
  • OfStack

The try is like a net that nets all exceptions thrown by the code inside the try{} and then hands them off to the code inside the catch{} to handle. Finally, execute the code in finally. The code in finally must be executed regardless of whether the code in the try has an exception or whether the catch catches the exception.
While the default processor provided by the system during Java execution is useful for debugging, you usually want to handle exceptions yourself. This has two advantages: first, it allows you to correct errors. Second, it prevents the program from automatically terminating. Most users will be confused if your program stops and prints the stack trace every time an error occurs. Fortunately, you can easily avoid this situation.
To guard against and handle runtime errors, simply place the code you want to monitor in the try block. Immediately after the try block, specify the type of exception you want to catch in the catch clause
Example of error catching : 


try 
{ 
  code; //Put your own code in there;
} catch(e) //If there is an error in the above code, it is caught here
{ 
  alert(e.number); //Get error message
} 

 
Such as:


import java.io.*;//Call the IO package
 public class SimpleCharInOut
 {
 public static void main(String args[])
  {
   char ch=' ';//Define the character ch to start with ' '
   System.out.println(" Enter a character please");//Print Enter a character please on the screen
   try {//The code you want to monitor is placed in the try block. Immediately after the try block, specify the type of exception you want to catch in the catch clause
 
     ch=(char)System.in.read();//Assigns the characters entered from the keyboard to the ch
    }
   catch(IOException e) //If there is an error in the above code, it is caught here
    {  } ;//No action is taken after an error
 System.out.println("You're entered character : " + ch);//Print You're entered character on the screen:
 //And the value of ch
  }
 }

We are writing the Java try.. With catch, you often need to close some IO resources with a finally clause at the end, such as


InputStream is;
try{
  is=openInputStream();
  // do something
}catch(IOException e){
  e.printStaceTrace(e);
}finally{
  try{
    is.close();
  }catch(IOException e ){
  }
}

But even Java veterans occasionally make mistakes when using this pattern. The code above, for example, when openInputStream () function in the execution of exception is thrown, the variable is the value is null, the execution is the close () will throw a NullPointerException. Due to the subclass NullPoiterException not IOException, so it can't be catch block to catch, but directly to call level thrown out. An improved method is when close the flow to judging is not empty, but such code can appear very � windbag. Personally think that more elegant writing is called directly Commons - the IO package provides IOUtils. CloseQuitely () method to close the flow (or their packaging a closeQuitely () method).
Another benefit of writing this way is that it is less prone to errors when multiple IO resources are closed, such as the following code:


InputStream is;
OutputStream os ;
try{
  is=openInputStream();
  // do something
}catch(IOException e){
  e.printStaceTrace(e);
}finally{
  try{
    if (is != null ) is.close();
    if (os != null ) os.close();
  }catch(IOException e ){
  }
}

When is. Close () fails, os.close() cannot be executed, resulting in the resource referenced by the OS not being released.
Maybe Oracle thinks this try.. The catch... Boilerboard code for finally is so unnecessary that in JDK 7 the try clause has been modified to make the code look more compact and concise, without having to write some code to manually close the resource. For example, the above code can be changed under JDK 7 to:


try(
 InputStream is = openInputStream();
 OutputStream os = openOutStream();
){
 // do something 
}catch(IOException e){
  e.printStaceTrace(e);
}

Oracle puts the try (..) here The statement is called a try-with-resource statement. It is important to note that try(.. ) must be an instance of the java.io.AutoClosable interface, when exiting the try.. The JDK automatically calls the close() method when it catches a block. That is, resources in the try-with-resource statement are not limited to IO resources.
 
It is necessary to add some details about the try-with-resource statement:
The JDK ensures that the close() method of all resources is called, regardless of whether the close() method throws an exception, in the reverse order of the resource declaration

All exceptions thrown in the try-with-resource statement are caught. If more than one exception is thrown, the subsequent exception is suppressed in the previous exception, and the catch block ends up with only the exception that was thrown first. Can, in turn, by calling the Throwable class definition getSuppressed () be suppressed (suppress) anomalies.

Again, in the example above,
When exiting the try.. The JDK calls os.close(), then is.close(), and if both close() throw ioexceptions, the exception thrown by is.close() is suppressed in the exception thrown by os.close(), and the catch block catches only the exception thrown by os.close(). Can pass getSuppressed () method to get the is. Close the exception thrown by the ().

If IOException occurs when openInputStream() is called, openOutputStream() is not called, os.close() and is.close() are not called, and the catch block catches the exception that is thrown when openInputStream() is called.

If an IOException occurs when you call openOutputStream(), then is.close() is still called, & PI; If is.close() then throws an IOException(marked e2), e2 will be suppressed to e1, and the catch block will catch an e1 exception.

 
In addition to the modifications to the try block, JDK 7 also simplifies the catch section, allowing multiple catch clauses to be merged. Such as:


try(
 InputStream is = openInputStream();
 OutputStream os = openOutStream();
){
 // do something  
}catch(IOException | XMLParseException | XPathException e){
  e.printStaceTrace(e);
}
 

In addition, when you rethrow multiple exceptions, you no longer need to define the exception type in detail, the compiler already knows which exception you are throwing. You simply declare the exception that needs to be thrown when the method is defined. Such as


//Although Exception is used here to match the IOException thrown, the compiler knows that the Exception actually thrown to the upper level is IOException
    public void doIO() throws IOException {
      try{
        throw new IOException();
      }catch(Exception e){
        throw e;
      }
    }

PS: what benefits can I expect from this feature
 
JDK 7 also has other interesting syntax new features, such as binary literals, segmentation of long Numbers with underscores, type inference for generic parameters, switch support for string matching, and more. Now JDK 8 has introduced some useful features. Using syntax features appropriately and flexibly without having to worry about backward compatibility can make our code somewhat cleaner and more concise.


Related articles: