Black Horse programmer —————— > fix of exception handling

Source: Internet
Author: User
Tags finally block

-------Android Training, Java training, look forward to communicating with you! ----------

Java's exception mechanism mainly relies on the try, catch, finally, throw, throws five keywords, where the try keyword immediately after a curly brace of code block, called the Try block, which can throw an exception to the code. A catch corresponds to an exception type and a code block that indicates that the catch block is used to handle this type of code block. Multiple catch blocks can also be followed by a finally block, and finally blocks are used to reclaim the physical resources opened in the try block, and the exception mechanism guarantees that the finally block is always executed.

The throws keyword is primarily used in method signatures to declare exceptions that may be thrown by the method, whereas throw is used to throw an actual exception, and throw can be used as a statement, throwing a specific exception object.

Java7 further enhances the functionality of the exception handling mechanism, including a try statement with resources, capturing two new features for multiple exception catches, which are two features that can simplify exception handling very well.

Java divides the exception into two types, checked exceptions and runtime exceptions, and Java considers that checked exceptions are exceptions that can be handled during the compile phase, so it forces the program to handle all checked exceptions. The runtime exception does not need to be handled. Checked exceptions can alert programmers to the exceptions they may send.

Try {   // Business Implementation code       }catch(Exception e) {   alert input not valid    goto  retry    }

If an exception occurs when executing the business logic code in a try block, the system automatically generates an exception object that is presented to the Java runtime, which is called throw exception (throw)

When the Java Runtime environment receives an exception object, it looks for a catch block that can handle the exception object, and if a suitable catch block is found, the exception object is referred to the catch block, which is called a catch exception, and if the Java Runtime Environment cannot find the catch block that catches the exception, The runtime environment terminates and the Java program exits.

Before Java7, each catch block can catch only one type of exception: But starting with Java7, a catch block can catch multiple types of exceptions. There are two places to note when capturing multiple types of exceptions using a catch block.

1: When capturing multiple types of exceptions, multiple exception types are separated by a vertical bar |

2: When capturing multiple types of exceptions, the exception variable has an implicit final decoration, so the program cannot re-assign the exception variable.

The following procedure demonstrates the multiple exception captures provided by JAVA7.

 Public classMultiexceptiontest { Public Static voidMain (string[] args) {Try        {            intA = Integer.parseint (args[0]); intb = Integer.parseint (args[1]); intc = A/b; System. out. println ("The result of dividing the two numbers you entered is:"+c); }        Catch(indexoutofboundsexception| numberformatexception|arithmeticexception IE) {System. out. println ("The program has an array out of bounds, a numeric format exception, one of the arithmetic exceptions"); //When capturing multiple exceptions, the exception variable defaults to the final decoration//so the following code is wrong//ie = new ArithmeticException ("test");        }        Catch(Exception e) {System. out. println ("Location Exception"); //exception variable does not have a final decoration when capturing one type of exception//so the following code is completely correctE =NewRuntimeException ("Test"); }    }}

Access exception information:

If the program needs to access information about the exception object in the catch block, it can be obtained by accessing the exception parameter after the catch block. When the Java runtime decides to call a catch block to process the exception object, the exception object is assigned to the exception parameter after the catch block, which the program can use to get information about the exception.

All exception objects contain the following common methods.

GetMessage (): Returns the detailed description string for the exception

Printstacktrace (): Output trace stack information for this exception to standard error output

Printstacktrace (Printstrean s): Outputs the trace stack information for this exception to the specified output stream

Getstacktrace (): Returns the trace stack information for this exception

The following program shows how the program accesses exception information

 Public class accessexceptionmsg {    publicstaticvoid  main (string[] args)     {         Try        {            new fileinputstream ("A.txt");        }         Catch (IOException IoE)        {            System.out.println (ioe.getmessage ());            Ioe.printstacktrace ();     }}}

The above program calls the exception object's GetMessage () method to the details of the exception object, and also uses the Printstacktrace () method to print the trace information for the exception.

Use finally to reclaim resources

Sometimes, the program opens some physical resources (such as database connections, network connections, and disk files) in a try block, which must be explicitly reclaimed. Java's garbage collection mechanism does not reclaim any physical resources, and the garbage collection mechanism can only reclaim memory occupied by objects in heap memory.

Where do you recycle these physical resources? Ethical recovery in try blocks? Or is it recycled in a catch block? Assuming that a resource is reclaimed in a program try block, if a statement of the try block causes an exception, the other statements after the statement usually do not get the chance to execute, which causes the resource recycling statement that is behind the statement to be executed. If a resource is reclaimed in a catch block, the catch block may not be executed at all, which will result in the inability to reclaim these physical resources in a timely manner.

To ensure that the physical resources opened in the try block can be reclaimed, the exception handling mechanism provides a finally block. The finally block is always executed, regardless of whether the code in the try block is an exception or not, regardless of which catch block is executed, even if a return statement is executed in a try block or catch block. The complete syntax structure for Java exception handling is as follows:

Try {    // Business Implementation Code ...     .} Catch (subexception e) {    // exception handling block 1    ...} Catch (subexception e) {    // exception handling block 2    ...} finally {    // resource Reclaim block     ...}

Only the try block is required in the exception handling syntax structure, that is, if there is no try block, then there is no subsequent catch block and finally block: both the catch block and the finally block are optional, but the catch block and finally block appear at least one of them. Can also appear at the same time: you can have multiple catch blocks, catch blocks that capture the parent exception must be behind the catch subclass exception: But not only the try block, neither the catch block nor the finally block; multiple catch blocks must be located after the try block. The finally block must be located after all catch blocks.

Unless you call a method that exits a virtual machine in a try block, the catch block does not matter what code is executed in the try block, the catch block, and the finally of the exception handling occurs.

In general, do not use statements such as return or throw that result in the finalization of a method in a finally block, which, once used in a finally block, will cause the try block to be invalidated by the Return,throw statement in the catch block.

The exception-handling process code can be placed in any executable code, so the complete exception-handling process can be placed in a try block or in a catch block, and can be placed in a finally block.

Java7 a try statement that automatically closes a resource

When a program uses the finally block to close a resource, the program becomes unusually bloated. Java7 allows for a pair of parentheses immediately after the Try keyword, which can be declared to initialize one or more resources, where resources are those that must be explicitly closed at the end of the program, and the try statement automatically shuts down those resources at the end of the statement.

To ensure that the try statement can gracefully close the resource, these resource implementation classes must implement the Autocloseable or Closeable interface, and the close () method must be implemented to implement both interfaces.

The following procedure demonstrates how to use a try statement that automatically closes a resource

1  Public classAutoclosetest {2 3      Public Static voidMain (string[] args)throwsIOException4     {5         Try(//declaration, initialize two resources that can be closed6                 //The Try statement will automatically close both resources7BufferedReader br =NewBufferedReader (NewFileReader ("Autoclosetest.java"));8                 9PrintStream PS =NewPrintStream (NewFileOutputStream ("A.txt")))Ten         { One             //use of two resources A System.out.println (Br.readline ()); -Ps.println ("Butterfly Dream Fan Butterfly"); -         } the      -  -     } -  +}

The above program initializes two IO streams respectively, because the BufferedReader PrintStream implements the Closeable interface, and they are declared in a try statement and initialized, so the try statement automatically closes them. So the above procedure is safe.

A try statement that automatically shuts down a resource is equivalent to containing an implicit finally block (the finally block is used to close the resource), so the try statement can have neither a catch block nor a finally block. Of course, if the main program needs to, automatically close the resource's try statement can also take multiple catch blocks and a finally block.

Java7 almost all of the resource classes (including the various classes of file IO, JDBC programming connection,statement and other interfaces) have been rewritten, the rewritten resource classes have implemented the Autocloseable or closeable interface.

Black Horse programmer —————— > fix of exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.