The most detailed Java exception handling tutorial

Source: Internet
Author: User
Tags array length exception handling finally block getmessage stack trace terminates throw exception throwable


1. Preface

Try...catch...finally I'm afraid it's a familiar statement, and it's very simple to use, logically it seems to be easy to understand. However, I personally experience the "lesson" tells me that this thing is not as simple as the imagination, obedient. Don't believe it? So you look at the following code, "Guess" what will be the result of the execution? Do not look back at the answer, and do not execute the code to see the real answer oh. If your answer is correct, then you don't have to waste your time reading this article.


package Test;  
   
public class TestException {  
    public TestException() {  
    }  
   
    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;  
        }  
    }  
   
    public static void main(String[] args) {  
        TestException testException1 = new TestException();  
        try {  
            testException1.testEx();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}



What's your answer? Is the answer below?

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

If your answer is really as stated above, then you are wrong. ^_^, it is recommended that you take a closer look at this article or the above code in a variety of different situations to modify, execute, test, you will find that there are many things are not as simple as originally imagined. Now publish the correct answer:

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

Note:

Finally statement block should not appear and return should appear. The return ret above is best for other statements to handle the relevant logic.

2.JAVA exception

Exceptions refer to a variety of conditions, such as: File not found, network connection failure, illegal parameters, and so on. An exception is an event that interferes with the normal instruction flow while the program is running. Java describes a variety of exceptions through the many subclasses of the Throwable class in the API. Thus, the Java exception is an object, an instance of the Throwable subclass, which describes the error conditions that appear in a piece of code. When a condition is generated, an error throws an exception.

Java Exception class hierarchy diagram:



In Java, all exceptions have a common ancestor throwable (can be thrown). Throwable specifies the commonality of any problems that can be transmitted through a Java application by using the exception propagation mechanism available in the code.

Throwable: There are two important subclasses: Exception (Exception) and error (Errors), both of which are important subclasses of Java exception handling, each containing a large number of subclasses.

Error (Error): A bug that the program cannot handle, indicating a more serious problem running the application. Most errors have nothing to do with what the code writer does, but represent a problem with the JVM (the Java virtual machine) when the code is running. For example, a Java Virtual machine run error (virtual Machineerror) will appear outofmemoryerror when the JVM no longer has the memory resources needed to continue the operation. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread.

These errors indicate that the failure occurred on the virtual machine itself, or when the virtual machine attempted to perform an application, such as a Java Virtual machine run error (Virtual machineerror), class definition error (NOCLASSDEFFOUNDERROR), and so on. These errors are not available because they are beyond the control and processing power of the application, and are most of the conditions that are not allowed when the program is running. For a well-designed application, even if an error does occur, it should not, in essence, attempt to deal with the unusual conditions it causes. In Java, errors are described by subclasses of the error.

Exception (Exception): is an exception that the program itself can handle.

The Exception class has an important subclass of RuntimeException. The RuntimeException class and its subclasses represent errors raised by the JVM common operations. For example, if an attempt is made to use a null-valued object reference, a divisor of zero, or an array out of bounds, a Run-time exception (NullPointerException, ArithmeticException) and Arrayindexoutofboundexception are raised.

Note: Exceptions and errors differ: Exceptions can be handled by the program itself, and errors cannot be handled.

Typically, Java exceptions (including exception and error) are divided into both the available exceptions (checked exceptions) and the unpredictable exceptions (unchecked exceptions).

can be checked exception (compiler requirements must be disposed of the exception): the correct program in operation, it is easy to appear, reasonable capacity of the abnormal situation. Although the anomaly is abnormal, but to a certain extent its occurrence is predictable, and once this abnormal situation, it must take some way to deal with.

In addition to RuntimeException and its subclasses, other exception classes and their subclasses belong to the check exception. This exception is characterized by the Java compiler checking it, that is, when such an exception may occur in the program, either by using the Try-catch statement to catch it, or by using a throws clause declaration to throw it, otherwise the compilation will not pass.

Non-checked exceptions (compiler does not require mandatory disposition of exceptions): Include Run-time exceptions (RuntimeException and their subclasses) and errors (error).

Exception This exception is divided into two classes of run-time and non run-time exceptions (compilation exceptions). These exceptions should be handled as much as possible in the program.

Run-time Exceptions: All RuntimeException classes and their subclass exceptions, such as nullpointerexception (null pointer exception), indexoutofboundsexception (subscript out of bounds exception), and so on, these exceptions are not checked for exceptions, In the program, you can choose to capture or not to handle. These exceptions are usually caused by program logic errors, and the program should avoid the occurrence of such anomalies from the logical point of view as much as possible.

Run-time exceptions are characterized by the Java compiler not checking it, that is, when such an exception can occur in a program, even if it is not captured with a Try-catch statement, or thrown with a throws clause declaration, it is compiled.

Non-Run-time exceptions (compilation exceptions): Exceptions that are outside of runtimeexception and belong to the exception class and its subclasses on a type. From the program syntax point of view is the exception that must be handled, if not handled, the program can not compile. such as IOException, SqlException, and user-defined exception exceptions, typically do not customize check exceptions.

3. Handling of abnormal mechanisms

In Java applications, the exception handling mechanism is: Throw an exception, catch an exception.

Throws an exception: When a method throws an exception, the method creates the exception object and delivers the Run-time system, which contains exception information such as the exception type and the state of the program at the time the exception occurs. The runtime system is responsible for finding and executing code to dispose of exceptions.

Catch exception: After the method throws an exception, the runtime system moves to find the appropriate exception handler (exception handler). A potential exception handler is a collection of methods that are persisted in the call stack sequentially when an exception occurs. An exception handler is the appropriate exception handler when it can handle an exception type that matches the type of exception thrown by the method. The runtime system starts with the method in which the exception occurred, and then returns to the method in the call stack, until it finds a method that contains the appropriate exception handler and executes it. The runtime system terminates when the runtime system traverses the call stack without finding an appropriate exception handler. At the same time, it means the termination of the Java program.

For run-time exceptions, errors, or check exceptions, Java technology requires different ways of handling exceptions.

Due to the unpredictability of run-time exceptions, in order to implement applications more rationally and easily, Java rules that runtime exceptions are automatically thrown by the Java runtime system, allowing applications to ignore run-time exceptions.

For error that may occur in a method run, Java allows the method to not make any throw declarations when the method is not intended to be captured. Because most error exceptions are situations that can never be allowed to occur, they are also exceptions that a reasonable application should not catch.

For all of the available exceptions, Java stipulates that a method must be caught or declared outside of the method being thrown. That is, when a method chooses not to catch an exception that can be checked, it must declare that it will throw an exception.

The way to catch exceptions is to provide an exception handler that matches the type. The caught exception may be an exception thrown and thrown by its own statement, or an exception that is thrown by a calling method or a Java run-time system. That is, the exception that a method can catch must be the exception that the Java code throws on the premises. Simply put, the exception is always thrown first and then captured.

Any Java code can throw an exception, such as the code that you write, the code from the Java Development environment package, or the Java Runtime System. No matter who, you can throw an exception through a Java throw statement.

Any exception thrown from a method must use the throws clause.

Catch exceptions are implemented by TRY-CATCH statements or try-catch-finally statements.

In general, the Java rule: for an exception to be checked must be caught, or declared thrown. Allow RuntimeException and error to be ignored.

3.1 Catch Exceptions: try, catch, and finally

1.try-catch statement

In Java, exceptions are caught by Try-catch statements. Its general grammatical form is:

try {
An abnormal <span style= may occur "WIDTH:AUTO; Height:auto; Float:none "id=" 16_nwp "><a style=" Text-decoration:none "mpid=" "target=" _blank "href=" http:// Cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=15&jk=a5a28d23faff58ab&k =%b3%cc%d0%f2%b4%fa%c2%eb&k0=%b3%cc%d0%f2%b4%fa%c2%eb&kdi0=0&luki=2&n=10&p=baidu&q= 06011078_cpr&rb=0&rs=1&seller_id=1&sid=ab58fffa238da2a5&ssp2=1&stid=0&t=tpclicked3 _hc&tu=u1922429&u=http%3a%2f%2fwww%2eadmin10000%2ecom%2fdocument%2f5853%2ehtml&urlid=0 "id=" 16_NWL " ><span style= "color: #0000ff; font-size:14px;width:auto;height:auto;float:none;" > Program Code </span></a></span>
catch (Type1 id1) {
Catch and dispose of the exception types that are thrown by a try Type1
}
catch (Type2 Id2) {
Catch and dispose of the exception types that are thrown by a try Type2
}

A pair of curly braces after the keyword try packs a piece of code that may have an exception, called the monitoring area. An exception object is created when the Java method occurs during the run. Throwing exceptions out of the monitoring area, the Java Runtime system attempts to find a matching catch clause to catch the exception. If there is a matching catch clause, the exception handling code is run and the Try-catch statement ends.

The principle of matching is that if the exception object thrown is an exception class for a catch clause, or a subclass of the exception class, the resulting exception object is considered to match the type of exception caught by the catch block.

Example 1 captures the "divisor 0" exception thrown by the throw statement.

public class TestException {
public static void Main (string[] args) {
int a = 6;
int b = 0;
try {//try monitoring area

if (b = = 0) throw new ArithmeticException (); Throwing an exception through a throw statement
System.out.println ("A/b value is:" + A/b);
}
catch (ArithmeticException e) {//Catch catch exception
SYSTEM.OUT.PRINTLN ("The program has an exception, variable B cannot be 0.") ");
}
SYSTEM.OUT.PRINTLN ("The program ends normally.) ");
}
}

Run Result:

The program has an exception and variable B cannot be 0.

The program ends normally.

Example 1 is judged by the IF statement in the try monitoring area, when the "divisor 0" error condition is set up to cause the arithmeticexception exception, creates the ArithmeticException exception object, and throws the exception to the Java Run-time system by the throw statement, The system looks for a matching exception handler catch and runs the corresponding exception handling code, the printout "program is abnormal, and variable B cannot be 0." The Try-catch statement ends and the program flow continues.

In fact, the "divisor is 0" and so on ArithmeticException, is the Runtimexception subclass. Runtime exceptions are automatically thrown by the Run-time system and do not require the use of throw statements.

Example 2 captures the ArithmeticException exception thrown by a "divisor of 0" when the runtime system automatically throws.

public static void Main (string[] args) {
int a = 6;
int b = 0;
try {
System.out.println ("A/b value is:" + A/b);
catch (ArithmeticException e) {
SYSTEM.OUT.PRINTLN ("The program has an exception, variable B cannot be 0.") ");
}
SYSTEM.OUT.PRINTLN ("The program ends normally.) ");
}
}

Run Result:

The program has an exception and variable B cannot be 0.

The program ends normally.

The statement in Example 2:

System.out.println ("A/b value is:" + A/b);

A "divisor 0" error occurred in the run, throwing a ArithmeticException exception. The runtime system creates an exception object and throws the monitoring area, which in turn matches the appropriate exception handler catch and executes the appropriate exception handling code.

Because the cost of checking for run-time exceptions is much greater than the benefits of catching exceptions, runtime exceptions are not available. The Java compiler allows a run-time exception to be ignored, and a method can neither capture nor declare a Run-time exception.

Example 3 does not capture or declare a Run-time exception to throw.

public class TestException {
public static void Main (string[] args) {
int A, B;
A = 6;
b = 0; The value of divisor B is 0.
System.out.println (A/b);
}
}

Run Result:

Exception in thread ' main ' java.lang.ArithmeticException:/by zero
At Test.TestException.main (Testexception.java:8)

The example 4 program may have a divisor of 0 exceptions and an array subscript out of bounds.

public class TestException {
public static void Main (string[] args) {
int[] Intarray = new Int[3];
try {
for (int i = 0; I <= intarray.length; i++) {
Intarray[i] = i;
System.out.println ("intarray[" + i + "] =" + intarray[i]);
System.out.println ("intarray[" + i + "] modulo" + (i-2) + "value:"
+ intarray[i]% (i-2));
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println ("Intarray array subscript <span style=" Width:auto height:auto float:none; "id=" 12_nwp "><a style=" Text-decoration:none "mpid=" "target=" _blank "href=" http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001 &ch=0&di=128&fv=15&jk=a5a28d23faff58ab&k=%D4%BD%BD%E7&k0=%D4%BD%BD%E7&kdi0=0& luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=ab58fffa238da2a5& ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3a%2f%2fwww%2eadmin10000%2ecom%2fdocument% 2f5853%2ehtml&urlid=0 "id=" 12_NWL "><span style=" color: #0000ff; font-size:14px;width:auto;height:auto; Float:none; " > Bounds </span></a></span> exceptions. ");
catch (ArithmeticException e) {
System.out.println ("divisor is 0 exception.") ");
}
SYSTEM.OUT.PRINTLN ("The program ends normally.) ");
}
}

Run Result:

Intarray[0] = 0

Intarray[0] Modulus-2 value: 0

INTARRAY[1] = 1

INTARRAY[1] Modulus-1 value: 0

INTARRAY[2] = 2

Divisor is 0 exception.

The program ends normally.

Example 4 program may have a divisor of 0 exception, and may also appear array subscript out of bounds exception. The ArithmeticException exception type is first matched during program operation, so a matching catch statement is executed:

catch (ArithmeticException e) {
System.out.println ("divisor is 0 exception.") ");
}

It should be noted that once a catch catches a matching exception type, it enters the exception handling code. At the end of the process, it means that the entire Try-catch statement ends. Other catch clauses no longer have the opportunity to match and catch the exception type.

Java describes the type of exception through an exception class, and the hierarchy of the exception classes is shown in Figure 1. For exception programs with multiple catch clauses, you should try to put the catch clause of the underlying exception class in front of you as much as possible, and then try to put the catch clause of the exception class that captures the relatively high level behind. Otherwise, catch clauses that capture the underlying exception class may be masked.

The runtimeexception exception class includes various common exceptions to the runtime, ArithmeticException classes and ArrayIndexOutOfBoundsException classes are its subclasses. Therefore, the catch clause of the RuntimeException exception class should be put on the last side, or it may mask specific exception handling or cause compilation errors.

2. try-catch-finally Statement

The Try-catch statement can also include the third part, which is the finally clause. It indicates what should be done, regardless of whether an exception occurs. The general grammatical form of a try-catch-finally statement is:

try {
An abnormal <span style= may occur "WIDTH:AUTO; Height:auto; Float:none "id=" 10_nwp "><a style=" Text-decoration:none "mpid=" "target=" _blank "href=" http:// Cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=15&jk=a5a28d23faff58ab&k =%b3%cc%d0%f2%b4%fa%c2%eb&k0=%b3%cc%d0%f2%b4%fa%c2%eb&kdi0=0&luki=2&n=10&p=baidu&q= 06011078_cpr&rb=0&rs=1&seller_id=1&sid=ab58fffa238da2a5&ssp2=1&stid=0&t=tpclicked3 _hc&tu=u1922429&u=http%3a%2f%2fwww%2eadmin10000%2ecom%2fdocument%2f5853%2ehtml&urlid=0 "id=" 10_NWL " ><span style= "color: #0000ff; font-size:14px;width:auto;height:auto;float:none;" > Program Code </span></a></span>
catch (Type1 id1) {
Catch and handle the exception type thrown by a try Type1
catch (Type2 Id2) {
Catch and handle the exception type thrown by a try Type2
finally {
Block of statements that will be executed whether or not an exception occurs
}

Example 5 an exception handler with a finally clause.

public class TestException {
public static void Main (String args[]) {
int i = 0;
String greetings[] = {"Hello world!", "Hello World!!",
"HELLO World!!!"};
while (I < 4) {
try {
Pay special attention to the design of the loop control variable i to avoid causing infinite loops
System.out.println (greetings[i++]);
catch (ArrayIndexOutOfBoundsException e) {
SYSTEM.OUT.PRINTLN ("Array subscript <span style=" Width:auto; height:auto; float:none; "Id=" 9_nwp "><a style=" Text-decoration:none "mpid=" 9 "target=" _blank "href=" http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001 &ch=0&di=128&fv=15&jk=a5a28d23faff58ab&k=%D4%BD%BD%E7&k0=%D4%BD%BD%E7&kdi0=0& luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=ab58fffa238da2a5& ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3a%2f%2fwww%2eadmin10000%2ecom%2fdocument% 2f5853%2ehtml&urlid=0 "id=" 9_NWL "><span style=" color: #0000ff; font-size:14px;width:auto;height:auto; Float:none; " > Cross-border </span></a></span> anomaly ");
finally {
System.out.println ("--------------------------");
}
}
}
}

Run Result:

Hello World!

————————?

Hello World!!

————————?

HELLO World!!!

————————?

Array subscript out of bounds exception

————————?

In Example 5, pay special attention to the design of the statement block in the TRY clause and, if designed as follows, there will be a dead loop. If the design is:

try {
System.out.println (Greetings[i]); i++;
}

Summary:

Try block: Used to catch exceptions. 0 or more catch blocks can then be followed, and if there are no catch blocks, you must follow a finally block.
Catch block: Used to handle an exception that is caught by a try.
Finally block: The statements in the finally block are executed whether or not the exception is captured or handled. When a return statement is encountered in a try block or a catch block, the finally statement block is executed before the method returns. Finally blocks are not executed in the following 4 special cases:
1) An exception occurred in the finally statement block.
2 System.exit () exits the program in the previous code.
3 the thread in which the program is located dies.
4) Turn off the CPU.

3. Try-catch-finally rules (syntax rules for exception handling statements):

1 You must add a catch or finally block after a try. A try block can be followed by both catch and finally blocks, but at least one block.
2 must follow the block order: If the code uses both catch and finally blocks, the catch block must be placed after the try block.
3 The catch block is related to the type of the corresponding exception class.
4 a try block may have more than one catch block. If so, the first matching block is executed. That is, the Java Virtual Opportunity matches the exception type that is actually thrown in sequence with each catch code block, and executes the catch code block if the exception object is an instance of an exception type or its subclass, and no additional catch code blocks are executed.
5) can be nested try-catch-finally structure.
6 in the try-catch-finally structure, you can throw the exception again.
7) The execution finally is terminated in addition to the following: The JVM terminates prematurely (calls System.exit (int)), throws an unhandled exception in the finally block, the computer loses power, fires, or encounters a virus attack.

4. Execute order of try, catch, finally statement blocks:

1 When a try does not catch an exception: the statement in the TRY statement block is executed, and the program skips the catch statement block, executing the finally block and subsequent statements;

2) When the try catches the exception, this exception is not handled in a catch statement block: When a statement in a try statement block has an exception, and there is no catch statement block that handles the exception, the exception is thrown to the JVM, and the statement in the finally statement block is executed. However, the statement after the finally statement block will not be executed;

3) When the try catches the exception, there are cases in the catch statement block that handle this exception: in the TRY statement block, which is executed sequentially, when an exception is executed to a statement, the program jumps to the catch statement block and matches the catch statement block one at a time to find the handler that corresponds to the Other catch statement blocks will not be executed, and the statement after the exception in the TRY statement block will not be executed, and after the catch statement block executes, executes the statement in the finally statement block and executes the statement after the finally block of statement;

Illustrates the execution of a try, catch, finally statement block:

3.2 Throwing an exception

Any Java code can throw an exception, such as the code that you write, the code from the Java Development environment package, or the Java Runtime System. No matter who, you can throw an exception through a Java throw statement. Any exception thrown from a method must use the throws clause.

   1. Throws throws an exception

If a method may have an exception, but does not have the ability to handle the exception, you can declare the thrown exception with the throws clause at the method declaration. For example, the car may malfunction during operation, the car itself can not handle the fault, so let the driver to deal with.

The throws statement declares the type of exception to throw when the method is defined, and if the exception exception type is thrown, the method is declared to throw all exceptions. Multiple exceptions can be separated with commas. The syntax format for the throws statement is:

MethodName throws Exception1,exception2,.., Exceptionn
{
}

The throws Exception1,exception2,..., Exceptionn after the method name is the list of exceptions to which the declaration is to be thrown. When the method throws an exception from the list of exceptions, the method does not handle the exception of these types and their subclass types, and throws it to the method that invokes the method, which he handles. For example:

Import <span style= "Width:auto; Height:auto; Float:none "id=" 7_nwp "><a style=" Text-decoration:none "mpid=" 7 "target=" _blank "href=" http://cpro.baidu.com /cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=15&jk=a5a28d23faff58ab&k=java&k0= Java&kdi0=0&luki=10&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid= ab58fffa238da2a5&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3a%2f%2fwww%2eadmin10000 %2ecom%2fdocument%2f5853%2ehtml&urlid=0 "id=" 7_NWL "><span style=" color: #0000ff; Font-size:14px;width: Auto;height:auto;float:none; " >java</span></a></span>.lang. Exception;
public class TestException {
static void Pop () throws negativearraysizeexception {
Define method and throw Negativearraysizeexception exception
int[] arr = new int[-3]; Create an array
}

public static void Main (string[] args) {//Main method
try {//try statements handle exception information
Pop (); Call Pop () method
catch (Negativearraysizeexception e) {
System.out.println ("Exception thrown by pop () method");/output Exception information
}
}

}

After the exception is thrown to the caller by using the throws keyword, if the caller does not want to handle the exception, it can continue to throw up, but ultimately there is a caller who can handle the exception.

The pop method does not handle exception negativearraysizeexception, but is handled by the main function.

Throws the rule that throws an exception:

1 if the exception is not checked (unchecked exception), that is, error, runtimeexception or their subclasses, then you can not use the throws keyword to declare the exception to throw, the compilation can still pass smoothly, but at run time will be thrown by the system.

2 must declare any available exceptions (checked exception) that the method can throw. That is, if a method may appear to be subject to a verifiable exception, either capture it with a try-catch statement, or throw it with a throws clause declaration, causing a compilation error

3 only if an exception is thrown, the caller of the method must either process or throw the exception back. When the caller of the method is powerless to handle the exception, it should continue to be thrown instead of being swallowed.

4 The calling method must follow any processing and declaration rules that can be checked for exceptions. If you override a method, you cannot declare exceptions that differ from the override method. Any exception declared must be a class or subclass of the exception that is declared by the overridden method.

For example:

void Method1 () throws ioexception{}//Legal

Compilation error, must capture or declare throw IOException
void Method2 () {
Method1 ();
}

Legal, the declaration throws IOException
void Method3 () throws IOException {
Method1 ();
}

Legitimately, the declaration throws exception,ioexception is a exception subclass
void Method4 () throws Exception {
Method1 ();
}

Legal, capture IOException
void Method5 () {
try{
Method1 ();
}catch (IOException e) {...}
}

Compilation error, must capture or declare throw exception
void Method6 () {
try{
Method1 ();
}catch (IOException e) {throw new Exception ();}
}

Legal, the declaration throws exception
void Method7 () throws exception{
try{
Method1 ();
}catch (IOException e) {throw new Exception ();}
}

The basis for determining that a method may appear to be abnormal is as follows:

1 There are throw statements in the method. For example, the catch code block for the above Method7 () method has throw statements.

2 calls other methods, and other methods throw an exception with a throws clause declaration. For example, the Method3 () method invokes the Method1 () method, and the Method1 () method declaration throws IOException, so method3 may appear in the IOException () method.

   2. Throw an exception using throw

Throw always appears in the body of the function to throw a throwable type of exception. The program terminates immediately after the throw statement, the statement that follows it, and then the try block that contains the catch clause that matches it, in all the try blocks that contain it (possibly in the upper call function).

We know that an exception is an instance object of an exception class, and we can create an instance object of the exception class that is thrown through the throw statement. The syntax format of the statement is:

throw new Exceptionname;

For example, an exception object that throws a IOException class:

throw new IOException;

Note that throw can only throw an instance object that can throw a class throwable or its subclasses. The following actions are incorrect:

throw new String ("exception");

This is because string is not a subclass of the Throwable class.

If you throw a check exception, you should also declare the type of exception that the method might throw in the method header. The caller of the method must also check for exceptions thrown by the handle.

If all the methods are thrown on top of each other, the final JVM will handle it, and the process is simply to print exception messages and stack information. If an error or runtimeexception is thrown, the caller of the method can optionally handle the exception.

Package Test;
Import <span style= "Width:auto; Height:auto; Float:none "id=" 6_nwp "><a style=" Text-decoration:none "mpid=" 6 "target=" _blank "href=" http://cpro.baidu.com /cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=15&jk=a5a28d23faff58ab&k=java&k0= Java&kdi0=0&luki=10&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid= ab58fffa238da2a5&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3a%2f%2fwww%2eadmin10000 %2ecom%2fdocument%2f5853%2ehtml&urlid=0 "id=" 6_NWL "><span style=" color: #0000ff; Font-size:14px;width: Auto;height:auto;float:none; " >java</span></a></span>.lang. Exception;
public class TestException {
static int quotient (int x, int y) throws MyException {//define method throws exception
if (Y < 0) {//Determine if the parameter is less than 0
throw new MyException ("divisor cannot be negative"); Exception information
}
return x/y; return value
}
public static void Main (String args[]) {//Main method
int a = 3;
int b = 0;
The try {//Try statement contains statements that may have an exception
int result = Quotient (a, b); Call Method Quotient ()
catch (MyException e) {//Handle custom exceptions
System.out.println (E.getmessage ()); Output exception information
catch (ArithmeticException e) {//Handle ArithmeticException exception
SYSTEM.OUT.PRINTLN ("Divisor cannot be 0"); Output hint information
catch (Exception e) {//Handle other exceptions
SYSTEM.OUT.PRINTLN ("The program has other exceptions"); Output hint information
}
}

}
Class MyException extends Exception {//Create custom Exception class
String message; Defining a String type variable
Public myexception (String errormessagr) {//Parent class method
message = ERRORMESSAGR;
}

Public String GetMessage () {//overwrite GetMessage () method
return message;
}
}

   3.3 Abnormal chain

1 if quotient (3,-1) is invoked, a MyException exception occurs and the program is executed in a catch (MyException e) code block;

2 If the call to quotient (5,0), the "divisor is 0" error will cause ArithmeticException exception, belong to the Run-time exception class, the Java runtime system automatically thrown. The quotient () method does not capture the ArithmeticException exception, and the Java Runtime system will find the main method along the method call stack and upload the thrown exception to the caller of the quotient () method:

int result = Quotient (a, b); Call Method Quotient ()

Because the statement is in the try monitoring area, the arithmeticexception exception that is returned with a divisor of 0 is thrown by the Java runtime system and matches the catch clause:

catch (ArithmeticException e) {//Handle ArithmeticException exception
SYSTEM.OUT.PRINTLN ("divisor cannot be 0″);" Output hint information
}

The processing result is the output "divisor cannot be 0". Java, the processing mechanism of the upward transfer of abnormal information, forms the abnormal chain.

The look-up exceptions thrown by the Java method are passed to the call stack, along the hierarchy of the method call, to the processing-capable invocation method, up to the main method. If the exception is passed to the main method, and main does not have processing power, and the exception is not thrown through the throws declaration, a compilation error may occur.

3 If there are other exceptions, the catch (Exception e) will be used to catch the exception. Since Exception is the parent class of all exception classes, if you place a catch (Exception e) block of code in front of the other two blocks of code, the following code block will never be executed, so the order of the catch statements is not swap.

   common methods in the 3.4 Throwable class

Note: Parameter E of the exception type in parentheses behind the catch keyword. Exception is the variable type that the try code block passes to the catch code block, and E is the variable name. The statement "E.getmessage ()" In the Catch code block; For output error properties. Typically, exception handling uses 3 functions to get information about an exception:

Getcause (): Returns the reason that the exception was thrown. Returns null if the cause is not present or unknown.

Getmeage (): Returns the message information for the exception.

Printstacktrace (): The stack trace of an object is output to the error output stream as the value of the field System.err.

Sometimes in order to simply ignore the code after the catch statement, so the Try-catch statement becomes a device, once the program in the process of running an exception, will ignore handling exceptions, and the reason for the error is difficult to find.

   4.Java Common Exceptions

Some exceptions are provided in Java to describe frequently occurring errors, and some require a programmer to catch or declare them, and some to be automatically captured by the Java virtual machine. Common exception classes in Java:

1. RuntimeException Subclass:

1, Java.lang.ArrayIndexOutOfBoundsException

Array index out of bounds exception. Thrown when the index value of an array is negative or greater than or equal to the size of the array.

2, Java.lang.ArithmeticException

Arithmetic condition exception. For example: integers except 0.

3, Java.lang.NullPointerException

Null pointer exception. The exception is thrown when an application attempts to use null where the object is required. For example, invoking an instance method of a null object, accessing the properties of a null object, calculating the length of a null object, throwing null with the throw statement, and so on

4, Java.lang.ClassNotFoundException

The class exception was not found. This exception is thrown when an application attempts to construct a class based on a class name in the form of a string, and when the class file of the corresponding name is not found after traversing Classpah.

5, java.lang.NegativeArraySizeException array length is a negative anomaly

6, the Java.lang.ArrayStoreException array contains an exception thrown by an incompatible value

7. Java.lang.SecurityException Security exception

8, java.lang.IllegalArgumentException illegal parameter anomaly

2.IOException

IOException: An exception that may occur when manipulating input and output streams.

Eofexception file has ended exception

FileNotFoundException file did not find an exception

3. Other

ClassCastException type Conversion Exception class

Arraystoreexception array contains exceptions thrown by incompatible values

SQLException Operation Database Exception class

Nosuchfieldexception Field did not find an exception

The Nosuchmethodexception method did not find the thrown exception

NumberFormatException string to the exception thrown by the number

Stringindexoutofboundsexception string index out of range throw exception

Illegalaccessexception does not allow access to a class of exceptions

Instantiationexception when an application attempts to create an instance of a class using the Newinstance () method in the class class, and the specified class object cannot be instantiated, the exception is thrown

   5. Custom Exceptions

Exception classes that are built into Java can describe most of the anomalies that occur during programming. In addition, users can customize exceptions. User-defined exception class, just inherit the exception class.

Using custom exception classes in your programs can be roughly divided into the following steps.

(1) Create a custom exception class.
(2) throws an exception object through the Throw keyword in the method.
(3) If you handle an exception in a method that currently throws an exception, you can use the Try-catch statement to catch and process it, otherwise, at the declaration of the method, indicate the exception to be thrown to the method caller by the throws keyword, and continue with the next step.
(4) to catch and handle an exception in the caller who has an exception method.

The example "throw an exception using throw" is mentioned above.

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.