Java Exception Handling Exception

Source: Internet
Author: User

Java Exception Handling Exception

I saw a question from someone else's problem and asked Exception, that is, java Exception Handling. I also learned java Exception Handling before, but I checked it, after reading other people's blogs about exception Handling for writing, I found that I learned little about exception Handling. After reading so many blogs and materials, let me make a summary. Otherwise, my brain will be confused.

In java, the Exception ancestor is Throwable, and the direct subclass of Throwable is Exception and Error.

The Error indicates an Error. This Error is generally caused by jvm running. If this Error occurs, our program cannot solve it, such as memory overflow oom, heap Overflow. We don't have to deal with this type of error, so we can directly throw the jvm to report the error. We don't have to solve it.

Exception is an Exception, which can be classified into checking and non-checking exceptions. For example, the RuntimeException class and its subclass are non-checkable exceptions, which indicate runtime exceptions, arrays out-of-bounds, and NULL pointer exceptions. We can also ignore these exceptions and let the jvm throw exceptions on its own, of course, if we can foresee such exceptions, we 'd better check the program's judgment and make sure that the program is robust. Some such exceptions can be avoided. Effect java has such a processing recommendation. For details, refer to this book.

Another type of Exception is the check Exception, which is a subclass of the Exception class and Exception class except the RuntimeException class and subclass. Check exception, which must be processed or thrown; otherwise, the compiler reports an error.

 

The following keywords are generally used for exception handling: try, catch, finally, throws, and throw. I will explain them one by one.

Try:

Code that may throw an exception is generally placed in the try {} code block, for example:

 

try {
  int   i=2/0;t.test1();//System.out.println(kkk+st);} catch (Exception e) {// TODO Auto-generated catch blockSystem.out.println(i will catch you....);e.printStackTrace();}

 

 

The above code 2/0 will certainly throw an exception, so you need to put it in the try {} block. In the try block, if any row throws an exception, the code after the try block will not be executed and will directly enter the exception handling code block.

 

Catch:

The catch (Excetion e) {} structure is used to handle exceptions thrown in the try code block. There may be many catch code blocks, but note that when there are many catch code blocks, when the parameters in the catch object have a parent-child relationship, the parameters in the catch object must be child classes before them, and the parent class is behind them, because exceptions are matched sequentially by the catch code block, once the thrown exception is a subclass or similar type of the catch parameter, it can be processed by this catch code block. Other catch code blocks will not be processed even if they meet this condition, if you have a finally code block, you can directly enter the finally code block. If you do not have a finally code block, you can directly run the code behind the catch code block.

 

Finally:

A finally code block is a code block that must be executed in exception handling. If no exception is found, it is executed. If an exception exists, it is processed in the catch code block and processed in finally.

Note that if there is a return statement in the try code block, the code block in finally is executed first and then the return statement is executed.

Note that the return value of the function is the value at the top of the stack of the final active stack. If try performs return, I will also perform return in finally, then the return value in the finally code block is at the top of the stack, so the return value in finally will be returned. 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 running result is:

I am in finally

 

Note that I tested it here, so return is performed in finally. It is generally not recommended to return in finally.

 

 

Throws:

Throws is used in function name (parameter 1, parameter 2...) throws exception class 1, exception class 2, exception class 3 .....{}

Throws indicates that an exception may occur to this function, but the function does not handle the exception. The function throws an exception and submits the exception handling to the function call for processing. If the function is called, if not processed, you can throw it up... Wait until a try {} catch () {} exception is processed or thrown to jvm (this is not recommended ).

 

Package com. wj. exception; public class TestException3 {public String testException () throws Exception {/* try {return I am in try;} finally {return I am in finally;} */System. out. println (I do not handle the exception, I throw the exception up, throws); int I = 2/0; System. out. println (I will not be able to execute because of exceptions ....); Return I am throwing an exception using throws;} 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 do not handle exceptions. I throw exceptions up and throwsjava. lang. arithmeticException:/by zeroat com. wj. exception. testException3.testException (TestException3.java: 13) at com. wj. exception. testException3.main (TestException3.java: 24)


 

 

Throw:

Throw throws an exception class object, which is generally used in methods. When used in the try code block, you can directly access the catch code block for processing. For example:

 

Package com. wj. exception; public class TestException3 {public String testException () {try {throw new Exception (I is throw exception);} catch (Exception e) {System. out. println (the exception thrown by throw);} finally {System. out. println (I executed the finally code block);} System. out. println (exception handling is finished !!!); 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 throw exceptions.
I am executing the finally code block


Exception Handling is finished !!!
I am in finally

 

 

Throw manually throws an exception that needs to be searched from the inside out to the try code block. If no exception is handled, throws must be added to the method to throws the exception. See 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 executed the finally code block);} // System. out. println (exception handling is finished !!!); 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 cause an error in the compiler, prompting us to throw an Exception using throws, or change throw new Exception () for processing.

 
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 block e1.printStackTrace () ;}} finally {System. out. println (I executed the finally code block);} // System. out. println (exception handling is finished !!!); Return I am in finally;} public static void main (String [] args) {// TODO Auto-generated method stub TestException3 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 run the finally code block I am in finally


 

 

 

 

 

 

 

 

3

Or:

 

 
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 executed the finally code block);} // System. out. println (exception handling is finished !!!); Return I am in finally;} public static void main (String [] args) {// TODO Auto-generated method stub TestException3 te = new TestException3 (); try {System. out. println (te. testException ();} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();}}}

Output result:

 

 
I run the finally code block java. lang. Exceptionat com. wj. exception. TestException3.testException (TestException3.java: 11) at com. wj. exception. TestException3.main (TestException3.java: 28)

 

 

 

 

 

 

 

4

This change is very simple, but there is a more amazing way to make the compiler do not make mistakes, as shown below:

 

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); return I am in finally;} // System. out. println (exception handling is finished !!!); // 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 am executing the finally code block
I am in finally

 

 

 

No fourth code was found, and an exception was thrown out, but no exception information was output. In addition, if you change the function return value to void and do not use return in finally, an error is returned. I don't quite understand this. Is it possible to use throw to throw an exception in catch, after using the return statement in the finally code block, will it be processed? If it is processed, why can't we get the exception output, or is the output exception information overwritten in the stack? If you know what is going on, you can talk about it.

 

After reading the above, do you understand java exceptions?

My blog posts:

 

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 testException1 = new TestException1 (); try {testException1.testEx ();} catch (Exception e) {System. out. println (end); e. printStackTrace ();}}}

Can you tell the running result without looking at the answer? You can run it in your own compiler to check the result and debug it to see if it is the same as what you think.

 

 

 

 

 

 

 

The running result is 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 running process, but there are some doubts about the internal mechanism, as I said in 4, in finally, the return will overwrite the exception thrown by throw. If so, the above Code can analyze the output results in the same way as running. You can try it, communicate with each other.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Related Article

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.