Java Exception Handling

Source: Internet
Author: User

1. Catching Exceptions

When our program encounters an exception, the program is terminated.
If we do not want the program to be terminated, it is very simple to put a block of code with the possibility of an exception in the Try statement, and then catch the exception type that can occur inside the catch statement.
Try-catch statement: To catch all possible exception types, an exception of the same type can be used with just one catch.

try{//possible exception code block}catch (Exception1 e) {catch Exception1 type exception}catch (Exception2 e) {catch Exception2 type exception}catch (Exception3 e) { Catch Exception3 type of exception}//etc ...

both the Ps:try statement and the catch statement must have curly braces ({}), even if there is only one statement inside. A try statement cannot exist alone and must be followed by a catch statement or a finally statement
Try-finally statement: When you want the program to be an exception, you can still execute a piece of code with the try-finally statement

try{//code block that may occur}finally{//the code in the finally is always executed regardless of whether an exception is generated in the code block in the try

There is also the try-catch-finally statement, which is equivalent to the combination of the above two statements. At this point, the exception is caught in the catch statement, and the finally statement is always executed, regardless of whether the statement in the try produces an exception or if the exception is caught.

2. Throwing Exceptions2.1throws Throw Exception

When an exception is thrown with the throws declaration, the exception is given to the previous caller for processing. Throws throws an exception class, which is placed behind the method signature.

void play () {try {pain ();} catch (Throwable e) {e.printstacktrace ();//print exception trace Information}}void pain () throws throwable{        // Generate Exception Code}

The Play () method calls the pain () method, and the pain () method produces an exception, but does not handle it and throws it up to the method that called it, so the exception is handled in the play () method.
So what if we could have an exception in the main () method, and we would throw an exception with throws?

public class MyException {public static void main (string[] args) throws throwable{string str= "Hello"; Str.charat (10);}}

Output Result:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:String index out of Range:10
At Java.lang.String.charAt (Unknown Source)
At Com.t.myexception.main (myexception.java:6)

We clearly saw the program error. This is because the main () method does not have a superior caller, and the resulting exception is given to the Java compiler or the virtual machine for processing. Non-runtime exception compiler processing, do not let the program compile through. Runtime exception for Java Virtual machine processing, the JVM handles exceptions to exceptions by printing exception tracking stack information and terminating the program's operation.

PS: If the caller at the previous level does not handle the exception that is thrown by the call, the program will also be terminated.

2.2throw Throw Exceptionthrows an exception with throw, not an exception class, but an exception instance. The implication in the program is that an exception is automatically generated.

public class MyException {public static void main (string[] args) {throw new Stringindexoutofboundsexception ();}}

The result of the program output is:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException
At Com.t.myexception.main (myexception.java:5)
This indicates that the program has produced an stringindexoutofboundsexception exception at this point.

3. Abnormal loss

Let's take a look at this program.

public class MyException {public void play () throws Throwable{try{string str= "Lavor_zl"; Str.charat (;p Ain ();} catch (Stringindexoutofboundsexception e) {throw new Stringindexoutofboundsexception ();} catch (ArrayIndexOutOfBoundsException e) {throw new ArrayIndexOutOfBoundsException ();}} public void pain () throws arrayindexoutofboundsexception{try{int[] Array=new int[10];array[12]=2014;} catch (ArrayIndexOutOfBoundsException e) {throw new ArrayIndexOutOfBoundsException ();}} public static void Main (string[] args) {myexception my=new myexception (); try {my.play ();} catch (Throwable e) {E.printstac Ktrace ();}}}

Output Result:
Java.lang.StringIndexOutOfBoundsException
At Com.t.myexception.play (myexception.java:10)
At Com.t.myexception.main (myexception.java:26)
Calling the play () method will produce two exceptions, why the output only prints an exception tracking information. In fact, as long as the previous talk about the clear, you know why.
I'll analyze the reason now. When we run to "Str.charat (10);" In this line of code, the catch catches a stringindexoutofboundsexception exception and throws an instance of the stringindexoutofboundsexception exception, and the program should have been terminated. This auto-generated exception is not captured in the play () method.
However, because the play () method throws an exception with throws Throwable, the program is not terminated, but the exception is given to the upper caller of the play () method, which is handled by the main () method. Although the program was not terminated, because the play () method produced an exception that was not handled, it was thrown to its superior caller, the main () method. When an exception occurs, the code that is supposed to execute after the exception in the play () method is not executed.

After the above program is clear, this program will also be easy to understand, is a typical case of abnormal loss.

public class MyException {public void play () throws Throwable{try{pain ();} catch (ArrayIndexOutOfBoundsException e) {stringindexoutofboundsexception c=new stringindexoutofboundsexception (); throw C;}} public void pain () throws arrayindexoutofboundsexception{try{int[] Array=new int[10];array[12]=2014;} catch (ArrayIndexOutOfBoundsException e) {throw new ArrayIndexOutOfBoundsException ();}} public static void Main (string[] args) {myexception my=new myexception (); try {my.play ();} catch (Throwable e) {E.printstac Ktrace ();}}}

Output Result:
Java.lang.StringIndexOutOfBoundsException
At Com.t.myexception.play (Myexception.java:8)
At Com.t.myexception.main (myexception.java:23)
The result is only a trace of the exception is printed, which is a typical case of abnormal loss, which we often use to elicit the exception chain because it is closest to the anomaly.

4. Abnormal chain

Let's take a look at the following program, which uses the exception chain.

public class MyException {public void play () throws Throwable{try{pain ();} catch (ArrayIndexOutOfBoundsException e) {stringindexoutofboundsexception c=new stringindexoutofboundsexception (); C.initcause (e);//exception chain throw C;}} public void pain () throws arrayindexoutofboundsexception{try{int[] Array=new int[10];array[12]=2014;} catch (ArrayIndexOutOfBoundsException e) {throw new ArrayIndexOutOfBoundsException ();}} public static void Main (string[] args) {myexception my=new myexception (); try {my.play ();} catch (Throwable e) {E.printstac Ktrace ();}}}

Output Result:
Java.lang.StringIndexOutOfBoundsException
At Com.t.myexception.play (Myexception.java:8)
At Com.t.myexception.main (myexception.java:24)
caused by:java.lang.ArrayIndexOutOfBoundsException
At Com.t.myexception.pain (myexception.java:18)
At Com.t.myexception.play (myexception.java:6)
... 1 more
From the output you can see that the trace information of two exceptions is printed, because of the reason for the exception chain.
We also found that this program is only more than one line above the program "C.initcause (e);", this is the use of the exception chain, with the original exception to initialize the cause of the current exception.
The exception chain is characterized by all exceptions, because the Initcause () method is inherited from Throwable.

5. Classification of exceptions

The Throwable class is the parent class for all exceptions.
Throwable has two subclasses, error (Errors), and exception.
Exception there are non-runtime exceptions (compile exceptions) and run-time exceptions (RuntimeException).
Non-runtime exceptions need to be captured, otherwise the compiler will not let it pass. Run-time exceptions can be selected for capture processing or not handled. These exceptions are usually caused by a program logic error, and the program should avoid this kind of exception as much as possible from a logical point of view.

6. Custom Exceptions

We should inherit exception when we customize common exceptions, and define runtime exceptions to inherit RuntimeException.

/* Custom Exception Example */class MyException extends Exception{public myexception () {super ();}}


Java Exception Handling

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.