Handle errors with exceptions-Section 3 Capture and handle exceptions

Source: Internet
Author: User

This section describes how to use the try, catch, and finally blocks of the exception processor to compile the exception processor. The last example is to analyze what happened under different circumstances.
The following example defines and implements a class called listofnumbers. In the constructor of the class, listofnumbers creates a vector that contains ten consecutive integers from 0 to 9. The listofnumbers class also defines the class called writelist. this class writes this number into a text file named outfile.txt. This example uses the output class defined in Java. Io.
// Note: In this design, this class will not be compiled
Import java. Io .*;
Import java. util. vector;

Public class listofnumbers {
Private vector Victor;
Private Static final int size = 10;
Public listofnumbers (){
Victor = new vector (size );
For (INT I = 0; I <size; I ++ ){
Victor. addelement (New INTEGER (I ));
}
}

Public void writelist (){
Printwriter out = new printwriter (
New filewriter ("outfile.txt "));
For (INT I = 0; I <size; I ++ ){
Out. println ("value at:" + I + "=" +
Victor. elementat (I ));
}
Out. Close ();
}
}
In this example, the first line of the black text code calls a constructor that initializes a file output stream. If the file cannot be opened, the constructor throws an ioexception. The second line of the Code in the black text area calls the elementat method of a vector class. If its parameter value is too small (less than zero) or too large (greater than the number of elements currently contained in the vector ), then it throws an arrayindexoutofboundsexception exception.
If you try to compile the listofnumbers class, the compilation will print an error message about the exception thrown by the filewrite constructor. This is because the ioexception thrown by the construction is a compilation check exception. The arrayindexoutofboundsexception exception thrown by the elementat method is a runtime exception, while the Java programming language only requires the program to handle the compilation check exception, therefore, you can only get one error message.
Now that you are familiar with the listofnumbers class and know where exceptions are thrown in the program, you can write the exception processor into the Catch Block to handle those exceptions.
How to throw an exception
Before you can capture an exception, there must be code that throws this exception somewhere in the program. Any code can throw an exception: it can be your own code, or it can be the code in the package written by others (for example, the package provided together with the Java platform ), or the Java Runtime Environment. No matter what exceptions are thrown, throw statements must be used to throw the exceptions.
You may have noticed that the Java platform provides various exception classes. All these classes are subclasses of the throwable class, and they allow programs to distinguish between various types of exceptions that occur during program execution.
You can also create your own exception classes to describe the problems in your written classes. In fact, if you are a developer of a package, you may have to create a collection of your own exception classes, so that your users can distinguish whether the errors in your package come from the Java platform or other packages.
You can also create an exception chain, which is introduced in java standard edition 1.4. For more information, see "exception chain.

"Throw" Statement
All methods use the throw statement to throw an exception. The throw statement requires a separate throwable object, which is a subclass of any throwable class. The following classes are available:
Throw somethrowableobject;
Let's take a look at the throw statement in the context of the program. The following pop method deletes an execution class from a public stack. This method removes the elements from the stack and returns the deleted object.
Public object POP () throws emptystackexception {
Object OBJ;
If (size = 0 ){
Throw new emptystackexception ();
}
OBJ = objectat (size-1 );
Setobjectat (size-1, null );
Size --;
Return OBJ;
}
The pop method checks whether there are elements on the stack. If the stack is empty (that is, its size is equal to 0), the pop method will instantiate a new emptystackexception object (which is a member of Java. util) and throw it. The next section explains how to create your own exception classes. What you need to remember now is that you can only throw objects inherited from the java. Lang. throwable class.
Note that the declaration of the POP method contains a throws clause. Emptystackexception is a checked exception and is not caught by the POP method. Therefore, this method must use the throws sub-name to declare the type of the exception it throws.

Throwable class and its subclass

Objects inherited from the throwable class include direct subclasses (objects directly inherited from the throwable class) and indirect subclasses (Objects inherited from the Child classes of the throwable class ). This section describes the hierarchy of the throwable class and the main sub-classes. As you can see, throws has two direct subclasses: the error class and the exception class.

 

 

Error class
When a dynamic connection or other locating fails in the Java virtual machine, the Java Virtual Machine throws an error object. A typical summary program does not capture or throw an errors object.
Exception class
Most programs throw or capture objects derived from the exception class. An exception indicates that a problem has occurred, but it is not a serious system problem. Most programs you compile will throw or capture the exceptions object (instead of the errors object ).
On the Java platform, the exception class has many defined subclasses. These subclasses indicate various types of exceptions. For example, the illegalaccessexception exception class indicates that a special method cannot be found; The negativearraysizeexception class indicates that the program attempts to create an array with a negative size.
There is a special exception subclass: runtimeexception. This subclass is an exception that occurs inside the Java Virtual Machine during the running of the program. For example, the nullpointerexception class is a runtime exception class. This exception occurs when a method attempts to access a member of an object through a null reference. In the unchecked exceptions --- the controversy section, we will discuss why a typical program should not throw a runtime exception or a subclass exception object of the runtimexception class.

Controversial unchecked exceptions
The Java programming language does not require methods to capture or list running exceptions or errors, so programmers may be misled, compile code that only throws running exceptions or inherits all Exception subclasses from runtimexception. These two shortcuts allow programmers to write code that does not have to worry about compilation errors, it does not bother to specify or capture any exceptions. Although this method seems very convenient for programmers, it avoids the intention to capture or specify the necessary things, and may cause errors to programmers who use your classes.
Why does the designer decide to force a method to specify all unchecked exceptions that may be thrown within its range? Any exception thrown by a method is part of the common method programming interface. Method Callers must be aware of the exceptions thrown by this method so that they can decide what to do for these exceptions. These exceptions are similar to interfaces for writing methods, with their parameters and return values.
Next, your question may be: if it is such a good illustration of a method API, including the exception it can throw, why not specify a runtime exception? The problem described during runtime exception is the result of a design problem, and the API's Customer Code cannot expect to recover program execution from where the error occurs or use some methods to handle them. These problems include algorithm exceptions (for example, Division by zero), pointer exceptions (for example, accessing an object through an empty reference ), and index exceptions (for example, attempting to access an array through an out-of-bounds index ). Runtime exceptions may occur anywhere in the program, and there may be many in a typical program. Therefore, you have to add running exceptions in each method to reduce program transparency, the compiler does not require you to specify or capture runtime exceptions (although you can ).
A common case of throwing a runtime exception (runtimeexception) is when the user calls an incorrect method. For example, a method checks whether its parameters are valid. If a parameter is null, this method may throw an nullpointerexception. This is a non-check exception.
In general, the reason for not throwing a runtime exception (runtimeexception) or creating a runtime exception (runtimeexception) subclass is that you don't want to worry about specifying the exceptions that your method can throw.
The principle of an exception in use is: if the customer can be expected to recover from an exception, it is necessary to use a checkpoint exception. If a customer cannot do anything for a program recovered from an exception, the non-checked exception can be used.

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.