Java Exception Analysis

Source: Internet
Author: User
Tags exception handling getmessage throw exception throwable java throws
10.3 Throwing an exception

The concept of exception throwing has been mentioned in the previous section. If the exception thrown in the try block is not able to catch its catch block, or if the exception is caught but does not want to be processed immediately, Java immediately exits the method and returns it to the previous level, so that it can be recursively up to the most external level. Also, in the declaration of the method, you specify the possible exception in the method so that the caller of the method is prepared to handle the code for this exception, so that this type of exception is handled by the caller of this method. The caller may handle this exception on its own, or it may place the exception on its caller. The exception is traced until the code that handles it is found. If there is no code to catch and handle this exception, Java will end the execution of this program.

Therefore, when an exception that is checked is not directly captured in the method, the exception must be thrown to the upper caller with the throw statement. That is, you can explicitly throw an exception through the throw statement, and declaring this method in the method with throws will throw a type of exception.

This section describes the exception throw statement, the exception declaration, the Throwable class, and its subclasses. 10.3.1 Exception Throw statement

When an exception that is checked is not directly captured in a method, you must specify all the checked exceptions that it can throw. Two parts of the job of throwing an exception are to use the throws statement in its declaration to specify an exception that it can throw, while using the throw statement to throw an exception.

Declaring a possible exception in a method is intended to allow the method to tell the compiler what exceptions it might produce, requiring its users to consider handling these exceptions, so that the exception is processed in a timely manner, reducing the probability of a program crashing.

Situations where Java may throw exceptions include: The method that was invoked throws an exception, detects an error, throws an exception with the throw statement, and the program code has an error, resulting in an exception, such as an array out of bounds error, and a Java Run-time system that generates an internal error. When both of the current exceptions occur, you should tell the person who used this method to force Java to throw an exception. Because any method that throws an exception is a trap that causes the program to die, the program ends if there is no code to handle the exception thrown by the method. The following explains the throw statement and the throws declaration. 1. Throw Statement

When using the throw statement, you need a separate Throwable object, which is a subclass of any throwable class, and uses the following format.

Throw somethrowableobject;

The program terminates immediately after it runs to the throw statement, and the statement that follows does not execute, and then looks in all the try blocks that contain it to find the catch that contains it.

Now, look at the throw statement in the context of your program. The following pop method deletes an execution class from a public stack. This method executes from the element above the stack and returns the object being deleted, as shown in code 10-11.

Example of the code 10-11 throw statement

Public Object Pop () throws emptystackexception {

Object obj;

if (size = = 0) {

Throw statement

throw new Emptystackexception ();

}

obj = Objectat (SIZE-1);

Setobjectat (SIZE-1, NULL);

size--;

return obj;

}

In code 10-11, the Pop method checks to see if there are elements on the stack. If the stack is empty (that is, its size equals 0), the Pop method instantiates a new Emptystackexception object (which is a member of the Java.util) and throws it. In section 10.4, you'll explain how to create your own exception class. Only objects that inherit from the Java.lang.Throwable class can be thrown here. 2. Throws Statement

In code 10-11, a throws clause is included in the declaration of the pop method. Emptystackexception is a checked exception, and the Pop method does not catch this exception. Therefore, this method must use the throws statement to declare the type of exception that it throws.

The throws clause is used in the declaration of a method to specify the exceptions that may occur in the method.

The throws clause is formatted as shown in code 10-12.

"Code 10-12" throws Express Example 1

Type Method_name (arg_list) throws whcaexception{

......

}

For example, as shown in code 10-13.

"Code 10-13" throws Express Example 2

Class animation{

Public Image LoadImage (String s) throws Eofexception {

......

......

}

}

When you declare the LoadImage () method in code 10-13, you add a throws Eofexception exception throw declaration to indicate that a eofexception exception may be thrown in this method.

If a method may throw more than one exception, you can declare multiple exceptions in the throws clause of the method, separated by commas ",". Code 10-13 becomes as shown in code 10-14.

"Code 10-14" throws Express example 3

Class animation{

Public Image LoadImage (String s)

Throws Eofexception, malformurlexception{

......

......

}

}

Not all possible exceptions are specified in the declaration of the method, exceptions derived from the error class and exceptions derived from the RuntimeException class are not specified in the method declaration. These two types of exceptions belong to unchecked exceptions (unchecked exception). Another class of exceptions in the Java language is check exceptions (checked exception). Checking for exceptions is those that should be handled in the program, and not checking for exceptions are those that cannot be interfered with (such as an error class exception) or exceptions that can be avoided entirely under control, such as an array out of bounds error. The declaration of a method must indicate all possible check exceptions. About checking for exceptions and not checking for exceptions, as well as the error class, the exception class, etc. will be discussed in detail in the 10.3.2 section.

The exception that the method actually throws may be an instance of the exception class or its subclass specified in the throws clause. For example, in the declaration of a method, the method may produce IOException, but the exception that might be thrown may be an instance of the Eofexception class, all of which are ioexception subclasses.

Note: When a subclass's method overrides a superclass's method, the exception declared in the throws clause of the subclass method cannot be more than the exception declared in the superclass method, or a compilation error will result. Therefore, if the superclass's method does not have a throws clause, then the method that overrides it in the subclass cannot use the throws clause to indicate an exception. For interfaces, the situation is the same.

Let's look at an example, as shown in code 10-15.

"Code 10-15" throws Express Example 4

Import java.io.IOException;

public class exceptionuse{

public static void Main (string[] args) {

try{

System.out.println ("");

System.out.println ("Please enter some characters:");

String s = getinput ();

System.out.println ("");

System.out.println ("The characters you entered are:");

System.out.println (s);

}

catch (IOException e) {

System.out.println ("Sorry, but" +e.getmessage ());

}

}

Throws indicates that a IOException exception may be thrown

Static String GetInput () throws ioexception{

char[] buffer = new CHAR[20];

int counter = 0;

Boolean flag = true;

while (flag) {

Buffer[counter] = (char) System.in.read ();

if (buffer[counter]== '/n ')

Flag = false;

counter++;

if (counter>=20) {

IOException myexception = new IOException ("Buffer is full");

Throw myexception;

}

}

return new String (buffer);

}

}

The output of the program is shown in Figure 10-12.

Http://book.csdn.net/BookFiles/319/img/image017.jpg

Figure 10-12 throws Express Example 4 run result

In code 10-15, a Method GetInput () is declared to get the character entered from the keyboard and return as a string object. The program set the number of characters entered from the keyboard can not be more than 20, or throw a IOException exception. Because a IOException exception may be generated in the method GetInput (), and the method itself does not provide a capture statement, the exception must be specified in the declaration of the method with throws, such as:

Static String GetInput () throws IOException

In Method GetInput (), there are two places where an exception can occur, one is the read () method of the Java InputStream class. The InputStream class's Read () method has the following prototype.

public abstract int Read () throws IOException

This exception is not captured and handled in Method GetInput (), such as:

Buffer[counter] = (char) System.in.read ();

Another place that might produce an exception is the while loop in the method, in which a IOException exception is thrown if the number of characters entered is greater than 20, such as:

counter++;

if (counter>=20) {

IOException myexception = new IOException ("Buffer is full");

Throw myexception;

}

In method Main, you catch both exceptions and print out the exception information. If no exception occurs, the resulting input string is printed, such as:

catch (IOException e) {

System.out.println ("Sorry, but" +e.getmessage ());

} 3. Exception thrown

Thus, throwing an exception requires the following 3 steps.

(1) Determine the exception class.

(2) Create an instance of the exception class.

(3) throws an exception.

Once Java throws an exception, the method is not returned to the caller, so you do not have to worry about the return value or provide a default return value.

Here's an example, as shown in code 10-16.

"Code 10-16" Exception cast show example 1

public class Exceptionuse {

Methods that might throw exception classes

public static void ThrowException () throws IOException {

System.out.println ("Creates an IO exception and throws it below.") ");

Throw an exception

throw new RuntimeException ("MyException");

}

public static void Main (String [] args) {

try {

ThrowException ();

}

Catch exception

catch (IOException re) {

System.out.println ("Capture IO Exception:" +re);

}

}

}

The output of the program is shown in Figure 10-13.

Http://book.csdn.net/BookFiles/319/img/image018.jpg

Fig. 10-13 Exception Cast Example 1 run result

Code 10-16 calls the ThrowException () method in the main () function, which can be seen in the declaration of this method, and it may throw a IOException exception. Looking at the definition of this method, you can see that it instantiates a runtimeexception class using the new operator and throws it using the throw statement. When this method is invoked, the exception is thrown, the catch statement is captured, and the exception information is printed.

For example, in the method Testtrycatch () of code 10-4 in the 10.2.1 section, the exception IOException and illegalaccessexception are captured and processed. Another option, however, is to not handle the exception in method Testtrycatch () and leave the exception to the caller of the method. At this point, you need to specify this exception in the throws clause of the method Testtrycatch (). Change code 10-4 later as shown in code 10-17.

"Code 10-17" Exception cast show Example 2

public class exceptionuse{

public static void Main (string[] args) {

try{

Testtrycatch ();

}

Catch exception

catch (IOException e) {

System.out.println ("Catch" +e.getmessage () + "in Main ()");

}

}

static void Testtrycatch () throws ioexception{

try{

Throw an exception

throw new IOException ("Exception 1");

}

Catch exception

catch (IOException e) {

System.out.println ("Throw" +e.getmessage () + "

In Testtrycatch () ");

Catch exception temporarily unhandled, throw exception

throw new IOException ("Exception 1");

}

}

}

The output of the program is shown in Figure 10-14.

Http://book.csdn.net/BookFiles/319/img/image019.jpg

Fig. 10-14 Exception Cast Example 2 run result

Note: In the program, the exception static void Testtrycatch () throws IOException is thrown in the method declaration, so the outer method should be handled (using the Try-catch block in the main () method to catch the exception) if main () This outer calling method does not use a try-catch block to catch an exception, and the program will not compile. 10.3.2 Throwable class and its subclasses

All of the exception classes in the Java language are derived from the Throwable class. The Throwable class is the most efficient exception handling class provided by Java. Objects that inherit the Throwable class include direct subclasses (objects that inherit directly from the Throwable class) and indirect subclasses (objects that inherit from subclasses of the Throwable Class), as shown in Figure 10-15.

Http://book.csdn.net/BookFiles/319/img/image020.gif

Figure 10-15 Throwable class and its subclasses

As you can see from figure 10-15, the throws has two direct subclasses: the error class and the exception class.

(1) Error class. The error class and its subclasses are primarily used to describe errors in some Java Runtime system or resource exhaustion, such as a Java virtual machine that throws an error object when a dynamic connection fails in a Java virtual machine or when other positioning fails. Ordinary simple programs do not capture or throw errors objects, which means that ordinary programs cannot recover from such errors.

(2) Exception class. The exception class and its subclasses are different from the error class, which is a superclass of all standard exceptions that a normal program can recover from. Most programs throw or catch objects that are derived from the exception class. An exception indicates that a problem has occurred, but it is not a serious system problem. Most programs will throw or capture exceptions objects (rather than errors objects).

In the Java platform, the exception class has many subclasses that have already been defined. These subclasses describe the various types of exceptions that occur. For example, the Illegalaccessexception exception class explains that a particular method cannot be found; the Negativearraysizeexception exception class description program tries to create an array with a negative size.

Specifically, the exception class has two branches: classes derived from runtimeexception and classes that are not derived from the RuntimeException class, so the classification is based on the reason that the error occurred.

RuntimeException is the exception caused by incorrect programmer programming, while other exceptions are due to some unusual circumstances, not the error of the program itself, and if these anomalies do not occur, the program itself is still a good program.

RuntimeException is an exception that occurs within the Java Virtual machine during the program's operation. For example, the NullPointerException class is a Run-time exception class that occurs when a method attempts to access a member of an object through a null citation. Specifically, the errors of the RuntimeException class are mandatory type conversions, array access, and NULL pointer operations. Other exceptions (exceptions to the RuntimeException Class) include the file pointer out of bounds, the malformed URL, and an attempt to find an object representing its class class for a nonexistent class.

The exception of the RuntimeException class is the fault of the programmer, which, in theory, is checked and tested by the programmer to detect such errors.

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.