try is like a network, which nets all the exceptions thrown by the code in try{}, and then hands the exceptions to the code in catch{} for processing. Finally execute the code in finally. Regardless of whether there are exceptions in the code in the try, and whether the catch catch catches the exception, the code in finally will be executed.
While the preset processors provided by Java execution period systems are useful for debugging, you usually want to handle exceptions yourself. There are two advantages to doing this: First, it allows you to fix errors. Second, it can prevent the program from automatically termination. Whenever an error occurs, if your program stops and prints out a stack track, most users will be confused. Fortunately, you can easily avoid this situation.
To beware of and deal with execution period errors, just put the code you want to monitor in the try block. Immediately after the try block, specify the exception pattern error capture example you want to catch in the catch clause:
try { code; //Put your own code in it; } catch(e) //If there is an error in the above code, you will catch { alert(e.number); //Get the error message}
For example:
import java.io.*;//Calling the io package public class SimpleCharInOut { public static void main(String args[]) { char ch=' ';//Defining a character ch as ' System.out.prin tln(" Enter a character please");//Open Enter a character please try on the screen {//Please put the program code you want to monitor in the try block. Immediately after the try block, specify the exception pattern you want to capture in the catch clause ch=(char)System.in.read();// Assign the characters entered from the keyboard to ch } catch(IOException e) //If there is an error in the above code, you will catch { } here;//No operation after the error System.out.println("You're entered character:" + ch);//Output You're entered on the screen character: // and the value of ch} }
When we write Java try..catch, we often need to add finally clauses to close some IO resources, for example
InputStream is;try{ is=openInputStream(); // do something}catch(IOException e){ e.printStaceTrace(e);} finally{ try{ is.close(); }catch(I OException e ){ }}
But when using this pattern, even Java veterans occasionally make some mistakes. For example, in the above code, when the openInputStream() function throws an exception during execution, the value of the variable is still null. Execution is.close() will throw a NullPointerException. Since NullPoiterException is not a child of IOException class, therefore It cannot be caught by the catch block, but is directly thrown to the calling layer. An improved way of writing is to make non-empty judgments when closing the stream, but the code will appear very wordy. I personally think that the more elegant way of writing is to directly call the IOUtils.closeQuitely() method provided by the commons-io package to close the stream (or encapsulate a closeQuitely() method yourself).
There is another advantage of using this writing method, which is that it is not easy to make mistakes when closing multiple IO resources, 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 an error occurs in is.close(), os.close() cannot be executed, resulting in the resource referenced by os not being released.
Perhaps Oracle also thinks that this kind of try... catch... finally boilerplate code is too unnecessary, so I made some modifications to the try clause in JDK 7, eliminating the writing of some code that manually closes resources, making the code look more Compact and simpler. For example, the above code can be changed to:
try( InputStream is = openInputStream(); OutputStream os = openOutStream();){ // do something }catch(IOException e){ e.printStaceTrace(e);}
Oracle calls the try(..) statement here the try-with-resource statement. It should be noted that the objects referenced by variables in try(.. ) must be instances that implement the java.io.AutoClosable interface. When exiting the try..catch block, the JDK will automatically call the close() method. That is to say, resource in try-with-resource statements is not limited to IO resources.
Here it is necessary to provide some additional explanations for some details of the try-with-resource statement:
JDK ensures that the close() method of all resources is called regardless of whether the close() method throws an exception, and the order of the call is reversed from the order of the resource declaration.
All thrown exceptions in the try-with-resource statement will be caught. If multiple exceptions are thrown, the subsequent exception will be suppressed. In the previous exception, the catch block will only get the first exception thrown. The suppressed exception can be obtained by calling getSuppressed() defined by the Throwable class in turn.
The example above,
When exiting the try.. catch. block, JDK will call os.close() first, then is.close(). If both close() throws IOException, then is.close() thrown The exception will be suppressed (suppressed) in the exception thrown by os.close(). In the end, the catch block only catches the exception thrown by os.close(). You can get the exception thrown by is.close() through the getSuppressed() method.
If an IOException occurs when openInputStream() is called, then openOutputStream() will not be called, os.close() and is.close() will not be called, and the catch block catches the thrown when calling openInputStream() exception.
If an IOException occurs (indicated by the token e1), then is.close() will still be called. If is.close() throws an IOException (indicated by the token e2), then e2 will be suppressed. In e1, the exception caught by the catch block is e1.
In addition to remodeling the try block, JDK 7 also simplifies the catch part, allowing multiple catch clauses to be merged. for example:
try( InputStream is = openInputStream(); OutputStream os = openOutStream();){ // do something }catch(IOException | XMLParseException | XPathException e) { e.printStaceTrace(e);}
In addition, when you retweet multiple exceptions, you no longer need to define the exception type in detail. The compiler already knows which exception you are throwing. You just need to declare the exception that needs to be thrown when the method is defined. for example
// Although the exception is used here to match the thrown IOException, the compiler knows that the exception actually thrown to the upper layer is IOException public void doIO() throws IOException { try{ throw new IOException(); }catc h(Exception e){ throw e ; } }
PS: I can't think of any benefits this feature will bring
JDK 7 has other interesting new syntax features, such as binary literals, segmentation of long numbers with underscores, type inference of generic parameters, switch supports string matching, etc. Now JDK 8 has introduced some useful features. Without considering backward compatibility, appropriate and flexibly applying some syntax features can make our code appear clearer and more concise to a certain extent.