Download Exception Classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Exception
Introduction
An exception is an abnormal event that is likely to happen when a program is executing. For instance:
(a)
(b)
(c)
(d)
(e)
(f)
(g)
The computer could run out of memory. Not usually, but there is a possibility that it can happen.
Calling the parseInt( arg ) method with argument, arg, that cannot be parsed into an integer.
Dividing an integer value by zero.
Using an index that is outside the range of an array.
Accessing an ArrayList or a Vector that is empty.
Attempting to access a file that does not exists.
Attempting to access a file that is empty.
Exception must be distinguished from other types of programming errors. Programming errors can be categorized
into three types – syntax errors, logic errors, and runtime errors. Errors that occur during compilation are called
syntax errors or compilation errors. These errors result from the lack of compliance with the rules of the
programming language. Logic errors on the other hand occur when the program produces unintended results.
Runtime errors occur when the program attempts to perform tasks that are impossible. Against this background the
program terminates abnormally. If we analyze the examples above, we will see that those tasks are impossible to
done, hence, they are all runtime errors.
The concept of exception is a customary way in Java to indicate that an abnormal condition has occurred. When a
method encounters an abnormal condition that it cannot handle itself, it may throw an exception. Throwing an
exception is like tossing a ball out of a window hoping that there is someone outside there who will catch it.
The central mission of exception handling is to transfer control from where the error occurred to a section of the
program that can deal with the exception. The section of code that deals with the exception is called an exception
handler. When you program in Java, you must position exception handlers strategically, so that your program will
catch and handle all exceptions that are likely to be thrown.
Response to an Exception
A program can be made to:
(a) Ignore exceptions, in which case the program would abort, or produce incorrect result.
(b) The user could be allowed to fix the problem, but usually the user of the program is not a programmer.
(c) The programmer could design the program in such a way that if and when an exception occurs, program
control would pass the exception to an appropriate block of codes within the program where the exception
can be taken care of.
Understanding Runtime Errors
As mentioned earlier, runtime errors occur when a program attempts to perform tasks that are impossible. Listing 1
shows a program that simply reads integer values continuously. The program terminates if the number 4 is entered.
Simple enough!
During the execution of the program the string “w” was entered and stored in the variable s. See Figure 1. The
parseInt() method expects a string. This string must be a digit. By giving the method the string w becomes an
impossible task to be performed; hence this gives rise to runtime error – exception. The program terminates
abnormally. See Figure 2.
import javax.swing.JOptionPane;
class Exception
{
public static void main(String[] arg)
{
boolean done = false;
while (!done)
{
String s = JOptionPane.showInputDialog("Enter an integer");
int i = Integer.parseInt(s);
if (i == 4)
done = true;
}
}
}
Listing 1.
Figure 1. The string w was entered as input.
Figure 2.
Notice that several lines of information are displayed in Figure 2 in response to the invalid input. The first line tells
us why the program fails – NumberFormatException. The cause – the invalid input string, w. An impossible task;
it cannot be parsed into an integer value as we know it.
Exception Classes
In Java, exceptions are objects. Hence, when your program throws an exception, it throws an object. The object that
it throws must be a descendant of the base class (super class) called Throwable. The class Throwable serves as the
base class for an entire family of exception classes. This class and most members of its family are found in
java.lang. A small part of this family is shown in Figure 3.
Throwable
Error
OutOfMemoryError
Exception
…….
IOException
ArithmeticException
RuntimeException
……..
IndexOutOfBoundsException
Figure 3. Exception Hierarchy
As you have seen in Figure 3, Java divides exceptions into two broad categories, namely: Error and Exception.
Error refers to catastrophic events, from which the program is not likely to recover. The programmer cannot design
any code to deal with exceptions of this category. The only recourse is to check for design flaws within the program.
For example:
(a) ClassFormatError. This error is thrown when the Java Virtual Machine attempts to read a class file and
determines that the file is malformed or otherwise cannot be interpreted as a class file.
(b) VirtualMachineError. This error is thrown to indicate that that the virtual machine is broken or has run
out of resources necessary for it to continue operating.
(c) NoClassDefFoundError This error is thrown if the Java Virtual Machine or a class loader tries to load in
the definition of a class (as part of a normal method call or as part of creating a new instance using the new
expression) and no definition of the class could be found.
(d) OutOfMemoryError. This error it thrown when the Java Virtual Machine cannot allocate an object
because it is out of memory, and no more memory could be made available by the garbage collector.
Exception exceptions refer to abnormal conditions that must be caught and be dealt with. Exceptions of this
category can be dealt with by transferring control to a block of codes where the exception is expected and will be
dealt with. Exceptions of this category are:
(a) IndexOutOfBoundsException. This exception is thrown to indicate that an index of some sort (such as to
an array, to a string, or to a vector) is out of range.
(b) ArithmeticException. This exception is thrown when an exceptional arithmetic condition has occurred.
For example, an integer "divide by zero" throws an instance of this class.
(c) InstantiantionException. This exception is thrown when an application tries to create an instance of a
class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.
(d) ClassCastException. This exception is thrown to indicate that the code has attempted to cast an object to a
subclass of which it is not an instance.
In addition to throwing objects whose classes are declared in Java, you can throw objects of your own design. To
create your own class of Throwable objects, your throwable class must be a subclass of the Throwable family.
Procedure For Handling Exceptions
Central to the concept of exception handling is the try-throw-catch-fianlly sequence.




The try block. This block encloses the code that may generate an exception.
The throw clause. This is the statement which says what exception object is to be thrown. The operand of a
throw must be an object from Throwable family. This clause is optional.
The catch block. This block of code handles the exception. There can be more than one catch block
associated with a single try block.
The finally block that gets executed regardless of whether or not an exception is thrown. This block is
optional. If coded it must be placed after any catch block.
Figure 4 shows the general format for handling exceptions:
try
{
<statements>
}
catch(ThrowableObject e)
{
<handle exception>
}
:
:
finally
{
<handle exception>
}
Catch block(s) must be followed immediately after a try block. If the there are two or more catch blocks in a series,
each must be unique. That is the parameter of each catch block must be different. If there is a series of catch blocks,
they must be arranged in the order of, the most specific exception object to be caught, to the more general object.
The finally block is optional. There can only be one finally block associated with a try block. Whether or not an
exception is thrown, the finally block gets executed, if it is specified. If no handler is found, the application is
aborted.
Exception and Its Associated Packages
You can and should catch the exceptions that are represented by objects of classes derived from the class Exception.
There is a special set of exceptions in this category called RuntimeException. These exceptions are not to be
thrown. The java runtime system will spot them and throw them automatically. However, the programmer should
arrange to catch them and to deal with them. The following section outlines the subclasses of Exception and the
package in which they are found.
java.util Package

RunTimeException
o EmptyStackException
o NoSuchElementException
java.io Package

IOException
o EOFException
o FileNotFoundException
o InterruptdIOException
o UTFDataFormatException
java.lang Package






ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptException
NoSuchMethodException

RunTimeException
o ArithmeticException
o ArrayStoreException
o ClassCastException
o IllegalArgumentException
 IllegalThreadStateException
 NumberFormatException
o IllegalMonitorStateException
o IndexOutOfBoundsException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException
o NegativeArraySizeException
o NullPointerException
o SecurityException
java.net


IOException
o MalformedURLException
o ProtocolException
o SocketException
o UnknownHostException
UnknownServiceException
java.awt Package
 AWTException
More