The process of responding to anevent. Window programs aresaid
to be event-driven becausethey operate by performingactions in
response to events.
Contents The Delegation Event Model Event Classes Event
Listeners Adapter Classes Inner Classes Anonymous Inner
Classes
The Delegation Event ModelApplet is event-driven.Delegation
Event model: JDK 1.1 introduced
Event Classes
Event Classes
Event Listeners
Adapter Classes
Delegated Event Model
Inner Classes
Anonymous Inner Classes
Exception in Java are classifiedon the basis of the
exceptionhandled by the java compiler.
Contents: Exception Handling in Java I. Introduction II. Common
Exceptions III. Catching Exceptions IV. The Throwable Superclass V.
Effectively using try-catch VI. Final thoughts of Exceptions Type
of Built-In Exceptions I. Checked Exception II. Unchecked Exception
Exception Hierarchy
Contents:Exceptions MethodsCatching ExceptionsMultiple Catch
blocksThe throws/throw keywordsThe Finally keywordsDeclaring your
own exceptionJava Exceptions
Exception Handling in JavaI. Introduction An exception is an
error thrown by a class or method reporting an error in operation.
For example, dividing by zero is undefined in mathematics, and a
calculation can fail if this winds up being the case because of an
error in user input. In this particular case an ArithmeticException
is thrown, and unless the programmer looks for this exception and
manually puts in code to handle it, the program will crash stating
the exception thrown and a stack trace, which would be unhelpful to
a casual user of a Java program. If the programmer handles the
exception, he could deliver a useful error to the user and return
the user to the beginning of the program so that they could
continue to use it.
Exception Handling in JavaII. Common Exceptions There are many
different exceptions that can be thrown by a program, and the Java
API contains quite a few. A lot are contained in the default
package, java.lang; however, when you start using more
functionality such as AWT, Swing, or java.io, the packages may also
contain additional exceptions thrown by those libraries. As you
start expanding the functionality, it might be a good idea to look
at potential exceptions in the package and when they might be
thrown in the course of your application.
Exception Handling in JavaII. Common Exceptions Here is a
primer of some: ArithmeticException--thrown if a program attempts
to perform division by zero ArrayIndexOutOfBoundsException--thrown
if a program attempts to access an index of an array that does not
exist StringIndexOutOfBoundsException--thrown if a program attempts
to access a character at a non-existent index in a String
NullPointerException--thrown if the JVM attempts to perform an
operation on an Object that points to no data, or null
Continuation:
Exception Handling in JavaII. Common Exceptions
NumberFormatException--thrown if a program is attempting to convert
a string to a numerical datatype, and the string contains
inappropriate characters (i.e. z or Q)
ClassNotFoundException--thrown if a program can not find a class it
depends at runtime (i.e., the classs ".class" file cannot be found
or was removed from the CLASSPATH) IOException--actually contained
in java.io, but it is thrown if the JVM failed to open an I/O
stream As I said before, many different exceptions exist, and you
should probably use your API documentation to learn about
additional exceptions that may apply to your particular
application. Continuation:
Exception Handling in JavaIII. Catching Exceptions The java
language contains keywords used specifically for testing for and
handling exceptions. The ones we will be using here are try and
catch, and they must be used in conjunction with one another. They
sort of work like if-else: try{ /* Contains code to be tested */
}catch(Exception e){ /* Contains code to be executed if instanced
of Exception is caught */}
Exception Handling in JavaIII. Catching Exceptions The catch
statement can look for all exceptions, using the Exception
superclass, or it can catch a specific exception that you think
could be thrown in the code you are testing with the tryblock. You
can even have multiple catch blocks to catch and execute custom
code for a number of different errors. A good thing to note would
be that any particular exception that is caught is compared with
each catch statement sequentially; so it is a good idea to put more
generic exceptions, like Exception, towards the bottom of the list.
Continuation:
Exception Handling in JavaIV. The Throwable Superclass The
catch statement also stores an instance of the exception that was
caught in the variable that the programmer uses, in the previous
example Exception e. While all exceptions are subclasses of
Exception, Exception itself is a subclass of Throwable, which
contains a nice suite of methods that you can use to get all kinds
of information to report about your exceptions:
getMessage()--returns the error message reported by the exception
in a String printStackTrace()--prints the stack trace of the
exception to standard output, useful for debugging purposes in
locating where the exception occurred
Exception Handling in JavaIV. The Throwable Superclass
printStackTrace(PrintStream s)--prints the stack trace to an
alternative output stream printStackTrace(PrintWriter s)--prints
the stack trace to a file, this way you can log stack traces
transparent to the user or log for later reference toString()--if
you just decide to print out the exception it will print out this:
NAME_OF_EXCEPTION: getMessage(). Using the catch you now have
control over what the error message is and where it goes.
Continuation:
Exception Handling in JavaV. Effectively using try-catch In
this section, Im going to give you a few code samples on using
try-catch blocks to give you an idea of the flexibility you as a
programmer have over exceptions in your programs. The scenario is a
user has input a file name to a program of a file that does not
exist. In this scenario we are going to be using a text-based
program; however, in a graphical environment you can easily use the
catch block to draw dialog boxes. In the first example, we want to
print a useful error message and exit the program gracefully,
saving the user from the confusing stack trace with something
useful:
Exception Handling in JavaV. Effectively using try-catch try{
BufferedReader in = new BufferedReader(new FileReader(userInput));
System.out.println(in.readLine()) }catch(IOException e){
System.err.println(e.getMessage()); System.err.println("Error: " +
userInput + " is not a valid file. Please verify that the file
exists and that you have access to it."); System.exit(1); }
Continuation:
Exception Handling in JavaV. Effectively using try-catch Here,
System.err.println() prints the error message to standard error
output which is a high priority buffer that is used to report error
messages to the console. If youre being a good programmer, you have
separate methods that handle the different functionality of your
programs; this way you can easily start the program from a previous
place in the program before an exception occurs. In this next
example, the user inputs the filename through the function
getUserInput() elsewhere in the program; we want to report the
"helpful error message" to the user and return the user to a place
where he can enter a new filename. Continuation:
Exception Handling in JavaV. Effectively using try-catch try{
BufferedReader in = new BufferedReader(new FileReader(userInput));
return in.readLine(); }catch(IOException e){
System.err.println(e.getMessage()); System.err.println("Error: " +
userInput + " is not a valid file. Please verify that the file
exists and that you have access to it."); return
getFileInput(getUserInput()); } Continuation:
Exception Handling in JavaV. Effectively using try-catch Now
you have an idea of how you can control your programs once an
exception is thrown, and this should give you the basic idea of how
to work with exceptions in the Java language. Continuation:
Exception Handling in JavaVI. Final thoughts of Exceptions The
best way to prevent your application from crashing from exceptions
is to avoid exceptions in the first place. It is much more costly
for a system to catch and handle exceptions than to account for
potential errors directly in your code. A lot of times, an
exception can point to a problem in the programmers logic rather
than in the users use of the program. You should look for the cause
of exceptions, and try to understand why it occurred and make sure
that you really had considered everything. You will be making far
more resilient and robust applications. Continuation:
Types of Built In ExceptionI. Checked ExceptionThese exception
are the object of the Exception class orany of its subclasses
except Runtime Exception class.These condition arises due to
invalid input, problemwith your network connectivity and problem
indatabase.java.io.IOException is a checked exception.This
exception is thrown when there is an error ininput-output
operation. In this case operation isnormally terminated.
Types of Built In ExceptionList of Checked Exceptions Exception
Reason for Exception This Exception occurs when Java run-time
system fail to find theClassNotFoundException specified class
mentioned in the program This Exception occurs when you create an
object of an abstractInstantiation Exception class and interface
This Exception occurs when you create an object of an
abstractIllegal Access Exception class and interface This Exception
occurs when the method you call does not exist inNot Such Method
Exception class
Types of Built In ExceptionII. Unchecked ExceptionThese
Exception arises during run-time ,that occur dueto invalid argument
passed to method. The javaCompiler does not check the program error
duringcompilation.For Example when you divide a number by zero,
run-time exception is raised.
Types of Built In Exception List of Unchecked Exceptions
Exception Reason for Exception These Exception occurs, when you
divide a number by zeroArithmetic Exception causes an Arithmetic
Exception These Exception occurs, when you try to assign a
referenceClass Cast Exception variable of a class to an
incompatible reference variable of another class These Exception
occurs, when you assign an array which is notArray Store Exception
compatible with the data type of that array These Exception occurs,
when you assign an array which is notArray Index Out Of Bounds
Exception compatible with the data type of that array These
Exception occurs, when you try to implement an applicationNull
Pointer Exception without referencing the object and allocating to
a memory These Exception occurs, when you try to convert a string
variableNumber Format Exception in an incorrect format to integer
(numeric format) that is not compatible with each otherNegative
ArraySizeException These are Exception, when you declare an array
of negative size.
An exception is a problem that arises during the execution of a
program. Anexception can occur for many different reasons,
including the following: A user has entered invalid data. A file
that needs to be opened cannot be found. A network connection has
been lost in the middle of communications, or the JVM has run out
of memory.Some of these exceptions are caused by user error, others
by programmererror, and others by physical resources that have
failed in some manner.
Checked exceptions: A checked exception is an exception that
istypically a user error or a problem that cannot be foreseen by
theprogrammer. For example, if a file is to be opened, but the file
cannot befound, an exception occurs. These exceptions cannot simply
be ignoredat the time of compilation. Runtime exceptions: A runtime
exception is an exception thatoccurs that probably could have been
avoided by the programmer. Asopposed to checked exceptions, runtime
exceptions are ignored at thetime of compliation. Errors: These are
not exceptions at all, but problems that arisebeyond the control of
the user or the programmer. Errors are typicallyignored in your
code because you can rarely do anything about an error.For example,
if a stack overflow occurs, an error will arise. They are
alsoignored at the time of compilation.
All exception classes are subtypes of the java.lang.Exception
class. The exceptionclass is a subclass of the Throwable class.
Other than the exception class there isanother subclass called
Error which is derived from the Throwable class.Errors are not
normally trapped form the Java programs. These conditionsnormally
happen in case of severe failures, which are not handled by the
javaprograms. Errors are generated to indicate errors generated by
the runtimeenvironment. Example : JVM is out of Memory. Normally
programs cannotrecover from errors.The Exception class has two main
subclasses : IOException class andRuntimeException Class.
SN Methods with Description1 public String getMessage() Returns
a detailed message about the exception that has occurred. This
message is initialized in the Throwable constructor.2 public
Throwable getCause() Returns the cause of the exception as
represented by a Throwable object.3 public String toString()
Returns the name of the class concatenated with the result of
getMessage()4 public void printStackTrace() Prints the result of
toString() along with the stack trace to System.err, the error
output stream.5 public StackTraceElement [] getStackTrace() Returns
an array containing each element on the stack trace. The element at
index 0 represents the top of the call stack, and the last element
in the array represents the method at the bottom of the call
stack.6 public Throwable fillInStackTrace() Fills the stack trace
of this Throwable object with the current stack trace, adding to
any previous information in the stack trace.
A method catches an exception using a combination ofthe try and
catch keywords. A try/catch block is placed around the code
thatmight generate an exception. Code within a try/catch block is
referred to asprotected code, and the syntax for using try/catch
looks like the following: try { //Protected code
}catch(ExceptionName e1) { //Catch block } A catch statement
involves declaring the type of exception you are trying tocatch. If
an exception occurs in protected code, the catch block (or blocks)
thatfollows the try is checked. If the type of exception that
occurred is listed in acatch block, the exception is passed to the
catch block much as an argument ispassed into a method
parameter.
The following is an array is declared with 2 elements. Then the
code triesE to access the 3rd element of the array which throws an
exception. // File Name : ExcepTest.javaX import java.io.*; public
class ExcepTest{A public static void main(String args[]){ try{ int
a[] = new int[2];M System.out.println("Access element three :" +
a[3]); }catch(ArrayIndexOutOfBoundsException e){P }
System.out.println("Exception thrown :" + e);
System.out.println("Out of the block");L } }E This would produce
following result: Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
A try block can be followed by multiple catch blocks. The
syntax for multiple catch blockslooks like the following: try {
//Protected code }catch(ExceptionType1 e1) { //Catch block
}catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3)
{ //Catch block } The previous statements demonstrate three catch
blocks, but you can have any number of them after a single try. If
an exception occurs in the protected code, the exception is thrown
to the first catch block in the list. If the data type of the
exception thrown matches ExceptionType1, it gets caught there. If
not, the exception passes down to the second catch statement. This
continues until the exception either is caught or falls through all
catches, in which case the current method stops execution and the
exception is thrown down to the previous method on the call
stack.
E Here is code segment showing how to use multiple try/catch
statements.X tryA { file = new FileInputStream(fileName);M x =
(byte) file.read(); }catch(IOException i) {P i.printStackTrace();
return -1;L }catch(FileNotFoundException f) //Not valid! {
f.printStackTrace();E } return -1;
If a method does not handle a checked exception, the method
mustdeclare it using the throwskeyword. The throws keyword appears
at the end of amethods signature. You can throw an exception,
either a newly instantiated one or anexception that you just
caught, by using the throw keyword. Try to understand thedifferent
in throws and throw keywords. The following method declares that it
throws a RemoteException: import java.io.*; public class className
{ public void deposit(double amount) throws RemoteException { //
Method implementation throw new RemoteException(); } //Remainder of
class definition }
A method can declare that it throws more than one exception, in
which casethe exceptions are declared in a list separated by
commas. For example, the followingmethod declares that it throws a
RemoteException and anInsufficientFundsException: import java.io.*;
public class className { public void withdraw(double amount) throws
RemoteException, InsufficientFundsException { // Method
implementation } //Remainder of class definition }
The finally keyword is used to create a block of code that
follows a try block.A finally block of code always executes,
whether or not an exception has occurred.Using a finally block
allows you to run any cleanup-type statements that you want
toexecute, no matter what happens in the protected code. A finally
block appears at theend of the catch blocks and has the following
syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch
block }catch(ExceptionType2 e2) { //Catch block
}catch(ExceptionType3 e3) { //Catch block }finally { //The finally
block always executes. }
public class ExcepTest{E public static void main(String
args[]){ int a[] = new int[2];X try{ System.out.println("Access
element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException
e){A } System.out.println("Exception thrown :" + e);M finally{ a[0]
= 6; System.out.println("First element value: " +a[0]);P }
System.out.println("The finally statement is executed");L } }E This
would produce following result: Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6
The finally statement is executed
You can create your own exceptions in Java. Keep the following
points in mindwhen writing your own exception classes: All
exceptions must be a child of Throwable. If you want to write a
checked exception that is automatically enforced by theHandle or
Declare Rule, you need to extend the Exception class. If you want
to write a runtime exception, you need to extend
theRuntimeException class.We can define our own Exception class as
below: class MyException extends Exception{ } You just need to
extend the Exception class to create your own Exceptionclass. These
are considered to be checked exceptions. The
followingInsufficientFundsException class is a user-defined
exception that extends theException class, making it a checked
exception. An exception class is like any otherclass, containing
useful fields and methods.
// File Name InsufficientFundsException.java import java.io.*;
public class InsufficientFundsException extends Exception { private
double amount; public InsufficientFundsException(double amount) {
this.amount = amount; } public double getAmount() { return amount;
} } To demonstrate using our user-defined exception, the following
CheckingAccount class contains a withdraw() method that throws an
InsufficientFundsException.Continuation
// File Name CheckingAccount.java { import java.io.*;
if(amount