In the process of writing a program, we must ensure its robustness in addition to its functionality. One of them is to include the handling of exceptions. Java divides the non-normal case into exception and error. Where error errors cannot be repaired and cannot be captured. The anomaly mechanism has become a standard for determining whether a programming language is mature. Then we also need to write the procedure of the process of dealing with the exception of the mechanism. For example, write log records to facilitate troubleshooting, such as prompt error code to tell the user the cause of the error. It's a bit tedious to write about exception handling, though.
The exception mechanism of Java mainly relies on the five keywords of try, catch, finally, throw, throws. Java divides exceptions into checked and runtime exceptions. The checked exception is an exception that must be handled by the compile phase, or a program error cannot be compiled. It embodies the design philosophy of Java---Code that does not have perfect error handling will not be executed at all. However, most of the methods do not always know how to deal with the exception, so the checked anomaly reduces the productivity of the program and the execution efficiency of the code to some extent.
Syntax structure:
try{ //Business implementation code ... .} catch (Exception e) { //error handling code}finally{ //Resource Collection}
Chestnuts:
Public classDivtest {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method Stub Try { intA =integer.parseint (args[0]); intb =integer.parseint (args[1]); intC =a/b; System.out.println (c); } Catch(Indexoutofboundsexception IE) {System.out.println ("Array Out of Bounds"); } Catch(numberformatexception ne) {System.out.println ("Data Format exception"); } Catch(ArithmeticException ae) {System.out.println ("Arithmetic Exception"); } Catch(Exception e) {System.out.println ("Unknown Exception"); } }}
Note: All parent exception catch blocks should be placed after the subclass exception catch block.
JAVA7 provides a multi-exception-caught exception variable with an implicit final modification, separated by |
Access exception information:
All exception objects contain the following methods
GetMessage ()
Printstacktrace ()
Printstacktrace (PrintStream s)
Getstacktrace ()
Chestnuts:
Public classaccessexceptionmsg {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method Stub Try{FileInputStream fis=NewFileInputStream ("A.txt"); } Catch(IOException IoE) {System.out.println (Ioe.getmessage ()); Ioe.printstacktrace (); } }}
View Code
Use finally to reclaim resources
Public classFinallytest {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method StubFileInputStream FIS =NULL; Try{FIS=NewFileInputStream ("A.txt"); } Catch(IOException IoE) {System.out.println (Ioe.getmessage ()); //return;//forcing the method to return, but will definitely execute the finally codeSystem.exit (1);//finally will not be executed } finally { if(fis!=NULL) { Try{fis.close (); } Catch(IOException IoE) {ioe.printstacktrace (); }} System.out.println ("EXE finally"); //try to avoid writing return and throw statements in Finally, Try,catch will not be executed } }}
View Code
Note: Java7 enhances the function of the try statement---a pair of parentheses immediately after the try statement that declares, initializes one or more resources (database connection, network connection, and so on), and then closes those resources automatically at the end of the statement.
The prerequisite is that these resource classes implement the Autocloseable or closeable interfaces. Java 7 Almost overwrites all the "resource classes", implementing the Autocloseable or Closeable interface.
The difference between throw and throws
The idea of throws throwing an exception is that the current method does not know how to handle this type of exception, which is handled by the caller at the previous level. Throws declaration throws can only be used in method signatures, throw multiple exception classes with, separate. Once using throws, the program does not need to use try. Catch to catch the exception. Example: The main method does not know how to handle the exception and gives it to the JVM for processing. The JVM handles exceptions by printing the exception's trace stack information and terminating the program's operation.
Throw is when the program error, the system automatically run out of the exception. Throws an exception instance instead of an exception class, and throws only one exception instance at a time. In the case of a checked exception, the throw statement is either in the try block, the display captures the exception, or is placed in a method that is thrown by the throws declaration, which is handled by the caller of the method.
Custom exception Classes
To inherit the exception or runtime exception, you must provide two constructors, a parameterless, a string, string to describe the exception object's information.
Catch and throw combine to use
Exceptions can be handled in several ways, such as capturing processing within a method and handling callers.
Public classAuctiontest {Private Doubleinitprice=30.0; Public voidBid (String Bidprice)throwsauctionexception {DoubleD =0.0; Try{d=double.parsedouble (Bidprice); } Catch(Exception e) {e.printstacktrace (); Throw NewAuctionexception ("must be a number!"); } if(initprice>d) {Throw NewAuctionexception ("lower than auction price!"); } Initprice=D; } Public Static voidMain (string[] args) {auctiontest at=Newauctiontest (); Try{at.bid ("3"); } Catch(Auctionexception ae) {System.err.println (Ae.getmessage ()); } } }
View Code
Exception chain
Exception translation: captures the original exception, throws a new business exception, and the new business exception contains prompt information for the user.
One of 23 design modes: Responsibility chain mode
Chestnuts:
PublicCalsal ()throwssalexception{Try{ //business logic to achieve payroll settlement ...}Catch(SQLException sqle) {//record the original exception and leave it to the administrator...Throw NewSalexception ("An exception occurred accessing the database");}Catch(Exception e) {//record the original exception and leave it to the administrator...Throw NewSalexception ("The system has an unknown exception");}
Public class extends exception{publlic salexception () {};p ubllic salexception (String msg) {Super(msg);}; Publlic salexception (Throwable t) {super(t)};}
View Code
Java Exception Tracking Stack
Developers can find the source of the exception through Printstacktrace ().
Public classThreadexceptiontestImplementsrunnable{ Public voidrun () {FirstMethod (); } Public voidFirstMethod () {Secondmethod (); } Public voidSecondmethod () {intA =5; intB=0; intc=a/b; } Public Static voidMain (string[] args) {NewThread (Newthreadexceptiontest ()). Start (); }} results: Exception in thread"Thread-0" Java.lang.ArithmeticException:/by Zero at ExceptionHandling.ThreadExceptionTest.secondMethod (Threadexceptiontest.java:25) at ExceptionHandling.ThreadExceptionTest.firstMethod (Threadexceptiontest.java:19) at ExceptionHandling.ThreadExceptionTest.run (Threadexceptiontest.java:15) at Java.lang.Thread.run (Thread.java:745)
Exception Handling Rules
- Minimizing program code clutter
- Capturing and preserving diagnostic information
- Notify the right person
- End unusual activity in the right way
Do not overuse exceptions, only use exceptions for external, indeterminate, and predictable run-time errors.
The chunk of the try block is divided into a number of possible exceptions to the program paragraphs, and placed in the try block, respectively, capture processing.
After the catch to the exception, do not ignore, take appropriate measures such as:
- Handle exceptions, make appropriate repairs to exceptions, or bypass exceptions to continue, or prompt the user to re-operate ....
- Re-throws the exception and throws it to the upper caller, throwing the exception directly with the throws declaration
Java Error Handling