Java Exception Handling exception

Source: Internet
Author: User
Tags finally block throw exception throwable

I look at other people's face by the question of the exception, that is, Java exception handling, I have also learned Java exception handling, but I checked the next, read someone else's blog about the exception exception handling, I found that their learning is not strong, only learned a little fur just, After reading so many blogs and materials, I make a summary, or my brain is chaotic.

The exception ancestor in Java is the direct subclass of Throwable,throwable is exception and error.

Error through the word we know, is wrong, this error is generally caused by JVM operation error, this error, our program can not solve, such as memory overflow oom, heap overflow and so on. This error, we do not have to deal with, directly let the JVM throw an error, we can not solve the matter.

Exception Chinese meaning is abnormal, then exception is divided into examination and non-inspection anomalies. For example, the RuntimeException class and subclasses are non-inspection differences, indicating the runtime exception, there is an array out of bounds, null pointer exception, we can also do not handle, let the JVM itself throws an exception, of course, if we can foresee this anomaly, it is best in the program to check the judgment, The program writes robustly, and some of these exceptions can be avoided. Effect Java has this kind of processing recommendation, specific can look at this book.

Exception there is a class of check exceptions, which are other subclasses of the exception class and exception class except for the RuntimeException class and subclasses. Check for exceptions, you must do exception handling or throw, or the compiler will error.

Exception handling generally use the following several keywords Try,catch,finally,throws,throw, below I do a description.

Try

Code that might throw an exception is typically placed in a try{} code block, such as:

try {
  int   i=2/0;t.test1 ();//system.out.println ("KKK" +st);} catch (Exception e) {//TODO auto-generated catch BlockSystem.out.println ("I'll Catch You ..."); E.printstacktrace ();}


The above code 2/0 is bound to throw an exception, so it needs to be placed in the try{} block, in the try block, if the row throws an exception, then the code behind the try block will no longer execute and will go directly to the exception handling code block.


Catch:

catch (Excetion e) {} This structure is used to handle exceptions thrown in a try code block, there can be a lot of catch code blocks, but note that when there are many catch code blocks, and the parameters inside the catch have a parent-child relationship, The parameter inside the catch must be the subclass in front, the parent class is behind, because the catch code block appears in order to match the thrown exception, once thrown the exception is which catch inside the parameters of the subclass or homogeneous, then it can be processed by this catch code block, Then the other catch code block even if the same conditions are not processed, if there is a finally block of code to go directly into the finally code block, not to run directly behind the catch code block code.


Finally

The finally code block is a block of code that is bound to be executed in exception handling, even if no exception is performed, and an exception is processed in the catch block after it is handled in the get into finally.

One thing to note here is that if there is a return statement in the try code block, then it is executed after the code block in finally executes the return statement.

It is also important to note that the return value of the function is the value of the top of the stack at the last active stack. If the try is returned, then I return in Finally, then the return value inside the finally code block is at the top of the stack, so it returns the value in finally. The following test code is available.

Package Com.wj.exception;public class TestException3 {public String testexception () {try{return ' I am in Try ';} Finally{return "I am in Finally";}} public static void Main (string[] args) {//TODO auto-generated method StubTestException3 te=new TestException3 (); System.out.println (Te.testexception ());}}


The operating result is:

I am in finally


Note that I am testing here so I return in Finally, it is generally not recommended to return in finally.



Throws

The use of throws is in the function name (parameter 1, parameter 2 ...). ) throws Exception Class 1, Exception Class 2, Exception Class 3 ..... {}

Throws is to indicate that this function may have an exception, but the function does not do exception handling, the function will throw an exception, the exception handling to the function of the call to handle, if the call, do not handle it can be thrown up ... Until there is a place to Try{}catch () {} exception handling, or finally to the JVM (it is not recommended).

Package Com.wj.exception;public class TestException3 {public String testexception () throws Exception{/*try{return "I am I n Try ";} Finally{return "I am in Finally";} */system.out.println ("I don't do exception handling, I'll throw an exception upward, throws"); int i=2/0; System.out.println ("There is an exception I will not be executed ....") "); return" I am using throws to throw the exception ";} public static void Main (string[] args) {//TODO auto-generated method StubTestException3 te=new TestException3 (); try {Syst Em.out.println (Te.testexception ());} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}


Output Result:

<span style= "FONT-SIZE:18PX;" > I don't do exception handling, I'll throw the exception up, Throwsjava.lang.ArithmeticException:/by Zeroat Com.wj.exception.TestException3.testException (testexception3.java:13) at Com.wj.exception.TestException3.main ( TESTEXCEPTION3.JAVA:24) </span>



Throw:

The function of throw is to throw an exception class object, which is usually used inside the method. When used in a try code block, directly into the catch code block for processing. Like what:

Package Com.wj.exception;public class TestException3 {public String testexception () {Try{throw New Exception ("I am throw E Xception ");} catch (Exception e) {System.out.println ("I handle exception thrown by throw");} FINALLY{SYSTEM.OUT.PRINTLN ("I execute the finally code block \ n");} SYSTEM.OUT.PRINTLN ("Exception handling ends!!! "); return" I AM in Finally ";} public static void Main (string[] args) {//TODO auto-generated method StubTestException3 te=new TestException3 ();    System.out.println (Te.testexception ());}}


Allowed results:

I handle the exception thrown by the throw
I execute a finally block of code


Exception handling end!!!
I am in finally



Throw the exception to be thrown manually from the inside to the outside to find the processing of the try code block, without processing, you need to add the method behind the throws, throw the exception up. Look at the following code:


1

Package Com.wj.exception;public class TestException3 {public String testexception () {Try{int i=3/0;} catch (Exception e) {throw new Exception ();} FINALLY{SYSTEM.OUT.PRINTLN ("I execute the finally code block \ n");} SYSTEM.OUT.PRINTLN ("Exception handling ends!!! "); return" I AM in Finally ";} public static void Main (string[] args) {//TODO auto-generated method StubTestException3 te=new TestException3 ();    System.out.println (Te.testexception ());}}





2

The above code will have an error in the compiler, prompting us to use throws to throw an exception, or The throw new Exception () is therefore processed and changed to such

<pre name= "code" class= "Java" >package Com.wj.exception;public class TestException3 {public String testexception ( ) {Try{int i=3/0;} catch (Exception e) {try {throw new Exception ()} catch (Exception E1) {//TODO auto-generated catch Blocke1.printstacktrace ();}} FINALLY{SYSTEM.OUT.PRINTLN ("I execute the finally code block \ n");} SYSTEM.OUT.PRINTLN ("Exception handling ends!!! "); return" I AM in Finally ";} public static void Main (string[] args)  {//TODO auto-generated method StubTestException3 te=new TestException3 (); 
   system.out.println (Te.testexception ());}}


Output Result:

Java.lang.Exceptionat com.wj.exception.TestException3.testException (testexception3.java:11) at Com.wj.exception.TestException3.main (testexception3.java:32) I execute finally code block I am in finally









3

Or is that the case:

<pre name= "code" class= "Java" >package Com.wj.exception;public class TestException3 {public String testexception ( )  throws Exception{try{int i=3/0;} catch (Exception e) {throw new Exception ();} FINALLY{SYSTEM.OUT.PRINTLN ("I execute the finally code block \ n");} SYSTEM.OUT.PRINTLN ("Exception handling ends!!! "); return" I AM in Finally ";} public static void Main (string[] args)  {//TODO auto-generated method StubTestException3 te=new TestException3 (); 
   try {System.out.println (Te.testexception ())} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

Output Result:

I execute the finally code block Java.lang.exception<span style= "White-space:pre" ></span>at Com.wj.exception.TestException3.testException (testexception3.java:11) <span style= "White-space:pre" ></ Span>at Com.wj.exception.TestException3.main (testexception3.java:28)







4

This change, very simple, but there is a more wonderful method of modification, you can make the compiler error, as follows:

Package Com.wj.exception;public class TestException3 {public String testexception ()  {try{int i=3/0;} catch (Exception e) {throw new Exception ();} FINALLY{SYSTEM.OUT.PRINTLN ("I execute the finally code block \ n"); return "I am in finally";} SYSTEM.OUT.PRINTLN ("Exception handling ends!!! ");//return" I am in Finally ";} public static void Main (string[] args) {//TODO auto-generated method StubTestException3 te=new TestException3 ();    System.out.println (Te.testexception ());}}

Output:

I execute a finally block of code
I am in finally




found no fourth code, originally ran out of an exception, but did not output any of the exception information. And the function return value to void, in finally does not use return, then will error, this point I do not quite understand, do you use throw thrown in the catch exception, in the finally code block after using the return statement, it was processed? If it is handled, how can I not have abnormal output, or the output of the exception information in the stack is covered? Know what's going on with the friends, can communicate under.


Looking at the above, do you have some understanding of the exceptions in Java?

I see an example in the blog http://blog.csdn.net/hguisu/article/details/6155636, seemingly more classic, borrowed, the code is as follows:

Package Com.wj.exception;public class TestException1 {Boolean testEx () throws Exception {Boolean ret = true;  try {ret = testEx1 ();  } catch (Exception e) {System.out.println ("testEx, Catch Exception");  ret = false;  Throw e; } finally {System.out.println ("testEx, finally;  return value= "+ ret);  return ret;  }} Boolean TestEx1 () throws Exception {Boolean ret = true;  try {ret = testEx2 ();  if (!ret) {return false;  } System.out.println ("TestEx1, at the end of Try");  return ret;  } catch (Exception e) {System.out.println ("testEx1, Catch Exception");  ret = false;  Throw e; } finally {System.out.println ("testEx1, finally;  return value= "+ ret);  return ret;  }} Boolean TestEx2 () throws Exception {Boolean ret = true;  try {int b = 12;  int C;  for (int i = 2; I >=-2; i--) {c = b/i;  System.out.println ("i=" + i);  } return true;  } catch (Exception e) {System.out.println ("testEx2, Catch Exception");  ret = false; throw e;} finally {System.out. println ("testEx2, finally;  return value= "+ ret);  return ret; }}/** * @param args */public static void main (string[] args) {//TODO auto-generated method StubTestException1 Testexc  Eption1 = new TestException1 ();  try {Testexception1.testex ();  } catch (Exception e) {System.out.println ("End \ n"); E.printstacktrace (); }  }}

If you do not see the answer, you can say the results of the operation? You can go to your own compiler to run the next look at the results, under Debug, see if it is the same as you think.







The results of the above operation are as follows:

i=2
I=1
TESTEX2, catch exception
TESTEX2, finally; Return Value=false
TESTEX1, finally; Return Value=false
TestEx, finally; Return Value=false


I have debug, so I know the process of running, but for the internal mechanism, there is a bit of doubt, as I said in 4, finally in the return will overwrite throw throw exception, really is this, if so, The above code will be able to analyze and run the same output results, you can try to communicate with each other.



This article original, reprint please Ming: http://blog.csdn.net/j903829182/article/details/39808307






















































































































Java Exception Handling exception

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.