Exception Handling in Java programming ideas

Source: Internet
Author: User

1. After an exception is thrown

1). Use new to create an exception object on the object

2) terminate the current execution path

3). The reference to the exception object is displayed from the current environment.

4) The exception handling mechanism takes over the program and starts execution.Exception Handling Mechanism

2. There are two basic models in theory for Exception Handling

1 ).Terminate Model: Once an exception is thrown, it indicates that the error cannot be recovered and can be returned for further execution. It is more practical.

2 ).Recovery Model:Execute the program after exception handling. However, it may cause "coupling ".

3. custom exception class (with a constructor with parameters)

class SimpleException extends Exception{   public SimpleException(){}   public SimpleException(String msg){      super(msg);   }}public class SimpleExceptionDemo{   public void func() throws SimpleException{      System.out.println("Throw SimpleExceptionfrom func().");      throw new SimpleException();   }   public void func1() throws SimpleException{      System.out.println("ThrowSimpleException from func1().");      throw new SimpleException("Originated in func1()");   }   public static void main(String[] args){      SimpleExceptionDemo sed = new SimpleExceptionDemo();      try {        sed.func();      } catch (SimpleException e) {        e.printStackTrace();      }      try {        sed.func1();      } catch (SimpleException e) {        e.printStackTrace();      }   }}

Running result:

4,Exception description: Practical keywordsThrows,The exception type that the client programmer may throw.

5. When defining abstract base classes and interfaces, You Can throwsSome exceptions that are not actually thrown. The advantage of doing so is that the exception occupies a seat first, and then the exception can be thrown without modifying the existing code.

6. CaptureAll exceptions(It is best to put it at the end of the handler list ):

catch (Exception e) {   System.err.println("Caught an exception");}

7. If the current exception object is re-thrown, The printstacktrace () method displays the call stack information of the original exception throw point instead of the information of the re-throw point. To update this information, you can callFillinstacktrace() Method, which returns a throwable object, which is created by filling the current call stack information with the original exception object.

8,

public static void main(String[] args) throws Throwable{      try{        throw new Throwable();      }catch(Exception e){        System.err.println("Caught inmain()");      }   }

Throwable is the base class of exception, so the following program won't be able to capture it in main.

9. runtimeexception (or any exception inherited from it) is a special case. For this exception, the compilerNo exception description is required.Cause:

1). Unexpected errors. For example, the null reference passed out of your control scope.

2). As a programmer, errors should be checked in the code. (For example, for arrayindexoutofboundsexception, pay attention to the array size .) Exceptions that occur in one place often lead to errors in another place.

10,Role of finally: Restores resources other than memory to their initial state. For example, the network connection of an opened file box, the drawing on the screen, or even a switch in the external world.

11,Exception loss:

class FirstException extends Exception{   public String toString(){      return "The firstException.";   }}class SecondException extends Exception{   public String toString(){      return "The secondException.";   }} public class ErrorFinally{   void firstFunc() throws FirstException{      throw new FirstException();   }   void secondFunc() throws SecondException{      throw new SecondException();   }   public static void main(String[] args) throws Exception{      ErrorFinally error = new ErrorFinally();      try {        error.firstFunc();      } finally{        error.secondFunc();      }   }}

Running result:

As you can see, firstexception is missing and is replaced by secondexception in finally.

12,Exception restrictions: When overwriting a method, only the exceptions listed in the exception description of the base class method can be thrown. This restriction is useful because it means that,When the code used by the base class is applied to the object of its derived class, it can work the same way (of course, this is the basic concept of object-oriented), and exceptions are no exception.

1) The exception description of the derived class constructor must contain the exception description of the base class constructor.

2). The derived class constructor cannot catch exceptions thrown by the base class constructor. (How do I understand the last sentence in the third section of p275 ??)

3). The method of the derived class can not throw an exception, even if the method of the base class throws an exception.

4). The method of the derived class can throw an exception inherited from the "exception thrown by the base class method.

See the following example:

Class baseexception extends exception {} class funcexception extends exception {} class otherfuncexception extends funcexception {} class base {base () throws baseexception {} void func () throws funcexception {system. out. println ("base. func () ");} void otherfunc () throws funcexception {system. out. println ("base. otherfunc () ") ;}} public class inheritbase extends base {// exception description of the derived class constructor must contain exception description of the base class constructor public I Nheritbase () throws baseexception {super () ;}// the method of the derived class does not throw an exception, even if the method of the base class throws an exception. Void func () {system. out. println ("inheritbase. func ");} // The method of the derived class can throw an exception inherited from the" exception thrown by the base class method, the following otherfuncexception inherits from funcexception // otherfuncexception is certainly captured because the exception handler can capture funcexception. Void otherfunc () throws otherfuncexception {system. out. println ("inheritbase. otherfunc () ");} public static void main (string [] ARGs) {try {base IB = new inheritbase (); IB. func ();} catch (baseexception e) {system. err. println ("caught baseexception. ");} catch (funcexception e) {system. err. println ("caught funcexception. ");}}}

13. Send the exception to the console

public static void main(String[] args) throws Exception{     }

14. Convert "Checked exceptions" to "non-checked exceptions ":Block the "Checked exceptions" feature.

1 ).

try {       } catch (BeCheckedException e) {   throw new RuntimeException(e);}

Benefits:You do not need to "vomit" an exception (the exception disappears completely after "vomit") or put it in the exception description of the method (throws ), the exception chain ensures that you do not lose any original exception information.

2) You can alsoDo not write try-catch statements and/or exception descriptionsDirectly ignore the exception and let it "bubble" up the call stack ". You can also use getcause () to capture and handle specific exceptions, as shown in the following example:

Class zeroexception extends exception {} class firstexception extends exception {} class secondexception extends exception {} class someotherexception extends exception {} // wrap the "Checked exception" to class wrapcheckexception {void throwruntimeexception (INT type) {try {Switch (type) {Case 0: Throw new zeroexception (); Case 1: Throw new firstexception (); Case 2: Throw new secondexception (); default: return ;}} catch (exception e) {Throw new runtimeexception (e) ;}} public class turnoffchecking {public static void main (string [] ARGs) {wrapcheckexception wce = new wrapcheckexception (); wce. throwruntimeexception (3); For (INT I = 0; I <4; I ++) {try {if (I <3) wce. throwruntimeexception (I); else throw new someotherexception ();} catch (someotherexception e) {system. out. println ("someotherexception:" + E);} catch (runtimeexception e) {try {// use getcause to catch a specific exception throw E. getcause ();} catch (zeroexception E1) {system. out. println ("zeroexception:" + E1);} catch (firstexception E1) {system. out. println ("firstexception:" + E1);} catch (secondexception E1) {system. out. println ("secondexception:" + E1);} catch (throwable E1) {system. out. println ("throwable:" + E1 );}}}}}

Running result:


1). wrapcheckexception. throwruntimeexception () wraps different exceptions into the runtimeexception object.

2) You can call throwruntimeexception () without using try blocks. However, you can also use try blocks to capture exceptions you want to catch.

3 ).In the programGetcause ()Result (that is, the packagedOriginal exception), And then use their own catch clauses for processing.

The above content is compiled from Java programming ideology. If any omission exists, please leave it blank.

I felt that my progress was a little slow. I wanted to read this book in one breath. How many more books do I have? 17 days. Only 267 pages are available now. I have to speed up !!

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.