2. The process of responding to an
event. Window programs are
said to be event-driven because
they operate by performing
actions in response to events.
3. Contents
The Delegation Event Model
Event Classes
Event Listeners
Adapter Classes
Inner Classes
Anonymous Inner Classes
4. The Delegation Event Model
Applet is event-driven.
Delegation Event model: JDK 1.1 introduced
12. Exception in Java are classified
on the basis of the exception
handled by the java compiler.
13. 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
15. Exception Handling in Java
I. 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.
16. Exception Handling in Java
II. 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.
17. Exception Handling in Java
II. 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:
18. Exception Handling in Java
II. 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 class's ".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:
19. Exception Handling in Java
III. “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
*/}
20. Exception Handling in Java
III. “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:
21. Exception Handling in Java
IV. 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
22. Exception Handling in Java
IV. 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:
23. Exception Handling in Java
V. Effectively using try-catch
In this section, I'm 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:
24. Exception Handling in Java
V. 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:
25. Exception Handling in Java
V. 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 you're
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:
26. Exception Handling in Java
V. 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:
27. Exception Handling in Java
V. 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:
28. Exception Handling in Java
VI. 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
programmer's logic rather than in the user's 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:
29. Types of Built In Exception
I. Checked Exception
These exception are the object of the Exception class or
any of its subclasses except Runtime Exception class.
These condition arises due to invalid input, problem
with your network connectivity and problem in
database.java.io.IOException is a checked exception.
This exception is thrown when there is an error in
input-output operation. In this case operation is
normally terminated.
30. Types of Built In Exception
List of Checked Exceptions
Exception Reason for Exception
This Exception occurs when Java run-time system fail to find the
ClassNotFoundException
specified class mentioned in the program
This Exception occurs when you create an object of an abstract
Instantiation Exception
class and interface
This Exception occurs when you create an object of an abstract
Illegal Access Exception
class and interface
This Exception occurs when the method you call does not exist in
Not Such Method Exception
class
31. Types of Built In Exception
II. Unchecked Exception
These Exception arises during run-time ,that occur due
to invalid argument passed to method. The java
Compiler does not check the program error during
compilation.
For Example when you divide a number by zero, run-
time exception is raised.
32. Types of Built In Exception
List of Unchecked Exceptions
Exception Reason for Exception
These Exception occurs, when you divide a number by zero
Arithmetic Exception
causes an Arithmetic Exception
These Exception occurs, when you try to assign a reference
Class Cast Exception variable of a class to an incompatible reference variable of
another class
These Exception occurs, when you assign an array which is not
Array Store Exception
compatible with the data type of that array
These Exception occurs, when you assign an array which is not
Array Index Out Of Bounds Exception
compatible with the data type of that array
These Exception occurs, when you try to implement an application
Null Pointer Exception
without referencing the object and allocating to a memory
These Exception occurs, when you try to convert a string variable
Number Format Exception in an incorrect format to integer (numeric format) that is not
compatible with each other
Negative ArraySizeException These are Exception, when you declare an array of negative size.
33. An exception is a problem that arises during the execution of a program. An
exception 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 programmer
error, and others by physical resources that have failed in some manner.
34. • Checked exceptions: A checked exception is an exception that is
typically a user error or a problem that cannot be foreseen by the
programmer. For example, if a file is to be opened, but the file cannot be
found, an exception occurs. These exceptions cannot simply be ignored
at the time of compilation.
• Runtime exceptions: A runtime exception is an exception that
occurs that probably could have been avoided by the programmer. As
opposed to checked exceptions, runtime exceptions are ignored at the
time of compliation.
• Errors: These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer. Errors are typically
ignored 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 also
ignored at the time of compilation.
35. All exception classes are subtypes of the java.lang.Exception class. The exception
class is a subclass of the Throwable class. Other than the exception class there is
another subclass called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions
normally happen in case of severe failures, which are not handled by the java
programs. Errors are generated to indicate errors generated by the runtime
environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.
The Exception class has two main subclasses : IOException class and
RuntimeException Class.
36. SN Methods with Description
1 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.
37. A method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that
might generate an exception. Code within a try/catch block is referred to as
protected 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 to
catch. If an exception occurs in protected code, the catch block (or blocks) that
follows the try is checked. If the type of exception that occurred is listed in a
catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.
38. The following is an array is declared with 2 elements. Then the code tries
E to access the 3rd element of the array which throws an exception.
// File Name : ExcepTest.java
X 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
39. A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks
looks 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.
40. E Here is code segment showing how to use multiple try/catch statements.
X
try
A {
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;
41. If a method does not handle a checked exception, the method must
declare it using the throwskeyword. The throws keyword appears at the end of a
method's signature.
You can throw an exception, either a newly instantiated one or an
exception that you just caught, by using the throw keyword. Try to understand the
different 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
}
42. A method can declare that it throws more than one exception, in which case
the exceptions are declared in a list separated by commas. For example, the following
method declares that it throws a RemoteException and an
InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
43. 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 to
execute, no matter what happens in the protected code. A finally block appears at the
end 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.
}
44. 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
45. You can create your own exceptions in Java. Keep the following points in mind
when 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 the
Handle or Declare Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the
RuntimeException 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 Exception
class. These are considered to be checked exceptions. The following
InsufficientFundsException class is a user-defined exception that extends the
Exception class, making it a checked exception. An exception class is like any other
class, containing useful fields and methods.
46. // 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
47. // File Name CheckingAccount.java {
import java.io.*; if(amount <= balance)
public class CheckingAccount { balance -= amount; }
{ else
private double balance; {
private int number; double needs = amount -
public CheckingAccount(int balance;
number) throw new
{ InsufficientFundsException(needs);
this.number = number; }
} }
public void deposit(double public double getBalance()
amount) {
{ return balance;
balance += amount; }
} public int getNumber()
public void withdraw(double {
amount) throws return number;
}
InsufficientFundsException }
Continuation
48. The following BankDemo program demonstrates invoking the deposit() and
withdraw() methods of CheckingAccount.
// File Name BankDemo.java
public class BankDemo c.withdraw(100.00);
{
public static void main(String [] System.out.println("nWithdrawing
args) $600...");
{ c.withdraw(600.00);
CheckingAccount c = new
CheckingAccount(101); }catch(InsufficientFundsException e)
System.out.println("Depositing {
$500..."); System.out.println("Sorry,
c.deposit(500.00); but you are short $"
try +
{ e.getAmount());
e.printStackTrace();
System.out.println("nWithdrawing }
$100..."); }
}
Continuation
49. Compile all the above three files and run BankDemo, this would
produce following result:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
Continuation
51. B
BatchUpdateException
BrokenBarrierException
C
CertificateException
ChangedCharSetException
CharConversionException
CharacterCodingException
ClassNotFoundException
CloneNotSupportedException
ClosedChannelException
D
DataFormatException
DatatypeConfigurationException
52. D
DestroyFailedException
E
EOFException
ExecutionException
ExpandVetoException
F
FileLockInterruptionException
FileNotFoundException
FishFaceException
FontFormatException
G
GSSException
53. G
GeneralSecurityException
I
IIOException
IOException
IllegalAccessException
IllegalArgumentException
IllegalClassFormatException
IllegalStateException
IndexOutOfBoundsException
InputMismatchException
InstantiationException
InterruptedException
55. L
LastOwnerException
LineUnavailableException
M
MalformedURLException
MarshalException
MidiUnavailableException
MimeTypeParseException
N
NamingException
NegativeArraySizeException
NoSuchElementException
NoSuchFieldException
NoSuchMethodException
57. P
PropertyVetoException
ProtocolException
R
RefreshFailedException
RemarshalException
RemoteException
RuntimeException
S
SAXException
SOAPException
SQLException
SQLWarning
SSLException
61. SAMPLE JAVA PROGRAM 1:
import java.io.*;
// A Java application to demonstrate making your own Exception class
// This program catches the exception when the word "client" is
// entered incorrectly.
public class TestException
{
static String s = "";
public static void main (String args[])
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(is);
System.out.println("Enter the word you cannot spell: ");
try
62. {
s = buf.readLine();
}
catch (IOException e)
{
System.out.println("IOException was " + e.getMessage());
}
try
{
checkSpelling(); // this method throws SpellException
}
catch (SpellException se) // but it is caught here
{
System.out.println("Spell exception was: " + se.getError());
}
} // end main
63. SAMPLE JAVA PROGRAM 2:
// Check spelling of typed in word. Throw exception if wrong.
// Note how this method specifies that it throws such and such
// exception. Does not have to be caught here.
private static void checkSpelling() throws SpellException
{
if (s.equalsIgnoreCase("client"))
System.out.println("OK");
else
throw new SpellException("Cannot spell client");
}
} // end main class