Thinking in Java --- Exception Handling Mechanism, thinkingjava ---

Source: Internet
Author: User

Thinking in Java --- Exception Handling Mechanism, thinkingjava ---

The exception handling mechanism of java can make the program have excellent fault tolerance and make the program more robust. the so-called Exception refers to the problem of blocking the execution of the current method or scope. When an Exception occurs during the program running, the system will automatically generate an Exception object to notify the program. this greatly simplifies our work.
Of course, there are many types of exception objects in java. The following figure shows the inheritance system of java exception classes.

From the picture, we can see that java divides all exceptions into two types: Exception and Error. They all inherit the Throwable parent class. errors generally refer to problems related to virtual machines, such as system crashes and Virtual Machine errors. this error cannot be recovered or cannot be captured, which will lead to application interruption. Generally, the application cannot handle these errors, so it should not try to catch them. exception can be captured and processed. the following describes the Exception Handling Mechanism in several aspects.

I. general format of Exception Handling

Try {// code that may throw exceptions} catch (Type1 id1) {// code that handles Type1 exceptions} catch (Type2 id2) {// code for handling type2 exceptions}

Place the code that may cause exceptions in the try block (but we do not know the specific exception ). if an exception occurs, the try block throws the exception object automatically generated by the system. Then, the exception handling mechanism searches for the first handler whose parameters match the exception type, then execute the catch Statement (which will not be searched down ). it seems similar to the switch statement. apart from the exception classes listed above, we can also define the exceptions and then process them. the most important thing to define an exception is the name of the exception class. in addition, the throws and throw keywords frequently occur in exception handling. throws indicates that the current program does not handle this exception and throws it to the upper-level program that calls this program for execution. If it is main () the method is passed to the JVM Virtual Machine for processing. throw explicitly throws an exception object. the following code uses the knowledge points mentioned above.

/// Define a simple exception class by yourself. You only need to declare the following inheritance relationships. // You can also write your own constructor, however, this is not a necessary public class SimpleException extends Exception {// public SimpleException (); // public SimpleException (String str) {// super (str )};} package lkl; import java. util. declare; public class ExceptionTest {// declare that this program will not handle SimpleException exceptions, but will throw it public void f () throws SimpleException {System. out. println ("Throws SimpleException from f ()"); // throw a SimpleException exception object throw new SimpleException ();} // multiple try statements are executed in sequence, even if an exception occurs in the previous try statement, the next try statement will execute public static void main (String [] args) {ExceptionTest et = new ExceptionTest (); try {et. f ();} // process the SimpleException exception thrown in try. catch (SimpleException sn) {System. out. println ("Catch it"); // call the printStackTrace () method of the exception class, by default, the error stream is printed to the standard error stream. // now, the specified output to the standard output stream is displayed. // The sequence of method calls from the method call point until the exception is thrown, the stack top is the last call, And the stack bottom is the first sn to be used. printStackTrace (System. out);} try {int [] a = new int [10]; Limit SC = new limit (System. in); System. out. println ("Enter k:"); int k = SC. nextInt (); SC. close (); System. out. println (a [k]);} // catch (ArrayIndexOutOfBoundsException AE) {System. out. println ("Catch ArrayIndexOutOfBoundsException"); AE. printStackTrace (System. out );}}}

Ii. Print exception information
The basic Exception of the Exception class provides a set of methods to  about the Exception. so if we get an exception object, we can print some useful information. The most common method is void printStackTrace, this method returns an array composed of elements in the stack track. Each element represents a frame in the stack. element 0 is the top element of the stack, and is the last method call in the call sequence (where this exception is created and thrown). It has several different overloaded versions, information can be output to different streams. the following code shows how to print basic exception information:

Package lkl; // common method for testing Exception-type exceptions public class ExceptionMethods {public static void main (String [] args) {try {throw new Exception ("My Exception");} // catch (Exception e) All types of exceptions can be caught by capturing the basic Exception of the Exception class. {System. out. println ("Caught Exception"); System. out. println ("getMessage ():" + e. getMessage (); System. out. println ("getLocalizedMessage ():" + e. getLocalizedMessage (); System. out. println ("toString ():" + e. toString (); System. out. println ("printStackTrace ():"); e. printStackTrace (System. out );}}}

Iii. rethrowing exceptions and exception chains
Sometimes you need to throw the caught exception again, which is quite simple in syntax. but the problem is that if the exception object is thrown directly, the information in this exception object will still be the information in the original exception object. if we want to update this information, we can call the fillInStackTrace () method. This method returns a Throwable object, which is obtained by filling the current call stack information into the original object. the line that calls fillStackTrace () becomes the new location of the exception. if another exception is thrown after an exception is captured, the information of the original exception occurrence point will be lost to obtain the same method as fillInStackTrace.
The so-called exception chain refers to throwing another exception after capturing an exception, and you want to keep the original exception information. the Throwable subclass in java can accept a cause object as a parameter in the constructor. this parameter is actually the original exception object, so that the original exception is passed to the new exception, even if a new exception is created at the current location, you can also trace the initial location of an exception through the exception link. however, in the Throwable subclass, only the constructor with the cause factor is provided for the Error, Exception, and RuntimeException subclasses. If you want to link other types of exceptions, you should use the initCause () method instead of the constructor.

4. Use finally for cleanup
The reason for the introduction of finally statements is that we want some code to always be executed, regardless of whether an exception is thrown in the try block. In this way, the basic format of exception handling is changed to the following:

Try {// code that may throw exceptions} catch (Type1 id1) {// code that handles Type1 exceptions} catch (Type2 id2) {// code for handling type2 exceptions} finally {// code that will always be executed}

In fact, only one catch or finally statement can appear. The following Code shows that the finally statement can always run.

Package lkl; public class FinallyTest extends Exception {public static int count = 0; public static void main (String [] args) {while (true) {try {// whether an exception is thrown or not, the finally statement will execute if (count ++ = 0) {throw new MyException ();} System. out. println ("No exception");} catch (MyException me) {System. out. println ("MyException");} finally {System. out. println ("In finally clause"); if (count = 2) break ;}}}}

The following code indicates that even if there is a return statement in try, the finally statement will still be executed, and it looks like there are multiple return points.

Package lkl; public class MultipleReturns {public static void f (int I) {System. out. println ("Initialization that requires cleanup"); try {// run System first before the reutrn function. out. println ("Point 1"); if (I = 1) return; System. out. println ("Point 2"); if (I = 2) return; System. out. println ("Point 3"); if (I = 3) return; System. out. println ("Point 4"); if (I = 4) return;} // before return, the finally statement finally {System is executed first. out. println ("Perferming cleanup") ;}} public static void main (String [] args) {for (int I = 1; I <= 4; I ++) f (I );}}

So what will the finally statement always be executed? In java, we are mainly used to clear other resources except memory. These resources include opened files or network connections, images drawn on the screen, etc.

V. Exception Handling and inheritance
The last question is about Exception Handling and inheritance. when Exception Handling and inheritance occur together, we need to pay attention to the relationship between the parent class constructor throwing an exception and the subclass constructor throwing an exception, how to declare an exception in the parent class method in the subclass. to sum up, there are actually two rules:
1). The exception thrown by the subclass override base class method must be no larger than the exception type thrown by the original base class method.
2 ). although the exception Declaration of the subclass constructor is not specified in syntax, the exception description of the subclass constructor must include the exception description of the base class constructor. (because the constructors of the base class are always called ).
The following code demonstrates this:

Public class Foul extends BaseballException {} public class PopFoul extends Foul {} public class extends Exception {} public class Strike extends BaseballException {} public class RainedOut extends StormException {} public interface Storm {public void event () throws RainedOut; public void rainHard () throws RainedOut;} public abstract class Inning {public Inning () throws BaseballException {} // throws an exception, however, there is actually no public void event () throws BaseballException {}; // The Declaration throws two exceptions: public abstract void atBat () throws Strike, Foul; public void walk () {}} public class StormyInning extends Inning implements Storm {public StormyInning () throws BaseballException, RainedOut {} public StormyInning (String s) throws Foul, baseballException {} // The method after the subclass overwrite is thrown because no exception is thrown in the base class method. // The compilation error is reported. // void walk () throws PopFoul {} // The interface cannot add an exception type to the base class method // public void event () throws RainedOut {} // The method to be rewritten throws the same exception as the method of the basic class. The public void rainHard () throws RainedOut {} // The method of the base class throws an exception, the override method does not throw public void event () {}// the override method can also throw the subclass of the base class exception. It is also possible to public void atBat () throws PopFoul {} public static void main (String [] args) {try {// the following two sentences may throw RainedOut In the constructor, baseballException exception // The atBat () method may throw a PopFoul exception. so we need to handle three exceptions: StormyInning si = new StormyInning (); si. atBat ();} catch (PopFoul e) {System. out. println ("Pop Foul");} catch (RainedOut e) {System. out. println ("Rained Out");} catch (BaseballException e) {System. out. println ("Generic baseball");} try {// This code is transformed upwards. Therefore, the base class atBat () must be processed in addition to the above three situations () strike exception thrown by the method Inning I = new StormyInning (); I. atBat ();} catch (Strike e) {System. out. println ("Strike");} catch (PopFoul e) {System. out. println ("Pop Foul");} catch (RainedOut e) {System. out. println ("Rained Out");} catch (BaseballException e) {System. out. println ("Generic baseball ");}}}


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.