Transcript document

Exception Handling
Exception Handling
1
Exceptions







Definition
Exception types
Exception Hierarchy
Catching exceptions
Throwing exceptions
Defining exceptions
Common exceptions and errors
Exception Handling
2
What is Exception?
Exceptions are unexpected conditions in a program
Exceptions happen at the different levels in a
program

They are usually handled at the different levels:
 Where they occur
 At another level
Exception examples:


Opening file that does not exist
Sending a message to an object that object does not
understand
Exception Handling
3
Exceptions in Java
In Java there are two different types of
exceptions:

Unchecked exceptions
 Runtime exceptions and errors

Checked exceptions
 All others exceptions
Exceptions are objects in Java and they
are all Throwable type
Exception Handling
4
Exception Hierarchy…
Checked, enforced
by Compiler
Throwable
Exception
Error
RuntimeException
Unchecked,
thrown by JVM
Exception Handling
5
…Exception Hierarchy
Throwable – top of the exception hierarchy in
Java, all exceptions are of this type
Error – represents serious problems in
program, that usually cannot be covered
from; thrown by the JVM
Exception – superclass for all exceptions
including user-defined exceptions
RuntimeException – also thrown by JVM and
caused by illegal operations
Exception Handling
6
Unchecked Exceptions
Exceptions that are thrown by the Java
Virtual Machine



Cannot be handled at the compilation as
compiler does not enforce developers to
handle exceptions
These exceptions occur at the runtime
Hard to catch specific unchecked exception
as they are not checked by the compiler
Exception Handling
7
Checked Exceptions
Exceptions checked by compiler


Need to be handled in the code as Compiler gives
a compile error if they are not handled
Exceptions are thrown by methods that are used
in the code
 That’s how Compiler recognizes them
What happens when exceptions are caught
depends on the exception handling strategy

Exception handling code defines how exceptions
are handled
Exception Handling
8
Handling Exceptions in Java
There are two different mechanisms for
handling Java exceptions:


Handling exceptions in a method where
they are caught
Propagating exceptions to the calling
method
 Calling method handles the exceptions
Which way you will handle exceptions
depend on the overall design of the
system
Exception Handling
9
try-catch block
Exceptions are handled in a try-catch block


Checked exceptions can be wrapped in a try-catch block
unless they are propagated to a calling method
Exceptions in a catch block can be any exception of
Throwable type public void myMethod()
{
try
{
//code that throws exception e
}
catch (Exception e)
{
//code that handles exception e
}
}
Exception Handling
10
Catching Multiple Exceptions
It is possible to catch multiple exceptions in a
catch block

Order of exceptions is important as more generic
exceptions should be handled at the end
public void myMethod()
{
try
{
//code that throws exception e1
//code that throws exception e2
}
catch(MyException e1)
{
//code that handles exception e1
}
catch(Exception e2)
{
//code that handles exception e2
}
}
Exception Handling
Exception
MyException
11
finally block
Executes always at the end after the last catch block

Commonly used for cleaning up resources (closing files, streams, etc.)
public void myMethod()
{
try
{
//code that throws exception e1
//code that throws exception e2
}
catch (MyException e1)
{
//code that handles exception e1
}
catch (Exception e2)
{
//code that handles exception e2
}
finally
{
//clean up code, close resources
}
}
Exception Handling
12
Propagating Exceptions
Can be used instead of try-catch block

Let the calling method handle the exception
Need to declare that method (in which code
is defined) throws the exception

Keyword throws is used in method declaration
public void myMethod() throws Exception
{
//code that throws exception e
}
Exception Handling
13
Handling Generic Exceptions
If you catch a generic exception that will
catch all the exceptions of that particular type

For example, catching Throwable will handle
checked and unchecked exceptions
public void myMethod()
{
try
{
//code
}
catch (Throwable e)
{
System.out.println(e.printStackTrace());
}
}
Exception Handling
14
Example : Divide by Zero (1)
public class DividebyZeroException extends ArithmeticException
{
public DividebyZeroException()
{
superclass
super( "Attempted to Divide by Zero" );
}
public DividebyZeroException( String message )
Call to superclass constructor
{
super( message );
}
}
The above code creates our own Exception Class,
which we will use to catch a specific type of error in
our program (see next slides)
Exception Handling
15
Example : Divide by Zero (2)
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class DividebyZeroTest
{
// Definition of method quotient. Used to demonstrate throwing an
exception
// when a divide-by-zero error is encountered.
public static double divide( int numerator, int denominator )
throws DividebyZeroException
Local method divide( )
which throws our own
{
Exception
if ( denominator == 0 )
throw new DividebyZeroException();
return ( double ) numerator / denominator;
} // End of method divide Exception Handling
16
Example : Divide by Zero (3)
public static void main(String[] args)
{
String input1, input2, output;
int number1, number2;
double result;
// Initialization
input1 = JOptionPane.showInputDialog(null,"Please Enter 1st Number
: ","Data Entry",JOptionPane.PLAIN_MESSAGE);
input2 = JOptionPane.showInputDialog(null,"Please Enter 2nd Number
: ","Data Entry",JOptionPane.PLAIN_MESSAGE);
DecimalFormat precision3 = new DecimalFormat( "0.000" );
Exception Handling
17
Example : Divide by Zero (4)
try {
number1 = Integer.parseInt( input1 );
number2 = Integer.parseInt( input2 );
Call to method divnums( )
result = divide( number1, number2 );
output = "Result : " + precision3.format(result);
JOptionPane.showMessageDialog(null,output,"Data Output“,
JOptionPane.INFORMATION_MESSAGE);
}
Exception Handling
18
Example : Divide by Zero (5)
catch ( NumberFormatException nfe )
{
JOptionPane.showMessageDialog(null, "You must enter 2 integers",
“Error Message", JOptionPane.ERROR_MESSAGE );
}
dbze.toString()
catch ( DividebyZeroException dbze )
{
JOptionPane.showMessageDialog( null, dbze,
“Error Message", JOptionPane.ERROR_MESSAGE );
}
System.exit(0);
} // End of main
} // End of Program
Exception Handling
19
Some Common Java
Exceptions
Unchecked, subclass of RuntimeException:

NullPointerException
 Thrown if a message is sent to null object

ArrayIndexOutOfBoundsException
 Thrown if an array is accessed by illegal index
Checked:

IOException
 Generic class for exceptions produced by input/output
operations

NoSuchMethodException
 Thrown when a method cannot be found

ClassNotFoundException
 Thrown when application tries to load class but definition
cannot be found
Exception Handling
20
Portion of Throwable
hierarchy
Throwable
Exception
Runtime
Exception
IOException
Error
AWTError
ArrayIndexOutOfBoundsException
ClassCastException
ThreadDeath
InputMismatchException
NullPointerException
Exception Handling
OutOf
MemoryError
ArithmeticException
21
Some Common Java Errors
NoSuchMethodError

Application calls method that no longer exist in the class
definition
 Usually happens if class definition changes runtime
NoClassDefFoundError

JVM tries to load class and class cannot be found
 Usually happens if classpath is not set, or class somehow gets
removed from the classpath
ClassFormatError

JVM tries to load class from file that is incorrect
 Usually happens if class file is corrupted, or if it isn’t class file
Exception Handling
22
Module Summary
In this module we have discussed:







What exceptions are
What types of exceptions exist in Java
Exceptions hierarchy
Catching exceptions
Throwing exceptions
Defining exceptions
Common exceptions and errors
Exception Handling
23