Chapter 13 Exception Handling
Download
Report
Transcript Chapter 13 Exception Handling
Chapter 13 Exception Handling
Claiming
Exceptions
Throwing Exceptions
Catching Exceptions
Rethrowing Exceptions
The finally Clause
Cautions When Using Exceptions
Exception Types
Mistakes happen
No matter how well designed a program is, there is
always the chance that some kind of error will arise
during its execution.
Attempting to divide by 0;
Attempting to read from a file which does not exist;
Referring to non-existing item in array;
etc.
An exception is an event that occurs during the
execution of a program that disrupt its normal
course.
Main idea
Java
was designed with the understanding that
errors occur, that unexpected events happened
and the programmer should always be prepared
for the worst.
The preferred way of handling such conditions
is to use exception handling, an approach that
separates a program’s normal code from its
error-handling code.
Example: Open file and read
contents
ask the user for the name of a file
open the file
read the contents
do something with the contents
close the file
Does the file exist?
Can we open the file?
Can we read data from the file?
Exceptions
Exception is a useful programming construct because
the location where an error is detected is usually not the
place where the appropriate solution is known.
Constructors are not permitted to return a null value,
furthermore there might be multiple reasons for a failure.
Does a null value returned by a file open operation
mean the file does not exist, or that it exists but cannot
be read? Finally, what if a null value is perfectly
legal?
Claiming, Throwing, and
Catching Exceptions
method1()
{
try
{
invoke method2;
}
catch (Exception ex)
{
Process exception;
}
catch exception
}
method2() throws Exception
{
if (an error occurs)
{
throw new Exception();
}
}
claim exception
throw exception
Example 1a: Division
When a statement causes error, the method containing
the statement creates exception object and passes it to the
system.
Class Test {
public static main(String args[]) {
int d, a;
d = 0;
a = 1/d;
}
}
Output:
java.lang.ArithmeticException: / by zero
at samples.Test.main(Test.java:5)
Exception handling
After a method throws an exception, the Java runtime
system begins the process of finding the code to handle
the error.
The code that handles the error is called the exception
handler; it is found by searching backward through a
chain of method calls, starting from the current method.
The process of finding a handler is called catching an
exception.
If no handler is found, the program terminates.
Example 1b: Division
int d, a;
d = 0;
try {
a = 1/d;
System.out.println(“It will not be printed”);
}
catch (ArithmeticException except) {
System.out.println(“Division by zero!”);
}
System.out.println(“After catch statement.”);
Output:
Division by zero!
After catch statement.
Example 1c: Division
int d, a;
d = 0;
try {
// The method now claims an exception and throws it if the divisor is zero.
if(d==0) throw new RuntimeException();
a = 1/d;
}
catch (RuntimeException except) {
System.out.println(except);
}
System.out.println(“After catch statement.”);
Output:
java.lang.RunTimeException
After catch statement.
Example 2: String to integer
String str1=“123”, str2=“xwz”;
try {
int i1 = Integer.parseInt(str1);
System.out.println(“The 1st int value ” + i1);
int i2 = Integer.parseInt(str2);
System.out.println(“The 2nd int value ” + i2);
}
catch (NumberFormatException exc) {
System.out.println(exc);
}
…
Output
The 1st int value is 123
java.lang.NumberFormatException: For input string: "xwz"
Exceptions handling
1. Claiming Exceptions
2. Throwing Exceptions
3. Catching Exceptions
1. Claiming Exceptions
To claim an exception in a method, use the throws
keyword.
modifiers MethodName(list of params) throws
Exception_1, Exception_2, ..., Exception_N
Example:
public void myMethod() throws IOException
{
...
}
Claiming Exception Example
// The method divide(k,m) returns result of division,
// n = k/m;
public int divide(int k, int m) throws
RuntimeException
{
...
}
2. Throwing Exceptions
In the method that has claimed the exception, you
can throw an object of the exception if the exception
arises.
throw new TheException();
TheException e = new TheException();
throw e;
Throwing Exceptions Example
public int divide(int k, int m) throws RunTimeException
{
if(m == 0)
{
throw new RuntimeException(”Divisor can’t be zero");
}
return k/m;
}
3. Catching Exceptions
try
{
statements;
}
catch(Exception1 e){
handler for exception1;
}
catch (Exception2 e) {
handler for exception2;
}
...
catch (ExceptionN e){
handler for exceptionN;
}
Catching Exceptions Example
try {
int n = divide(k,m);
}
catch(RuntimeException e){
System.out.println(“Error! Division by 0.”);
}
Methods of Exception object
public String getMessage()
// Returns detailed message of the object
public String toString()
// Returns short description of the object
public void printStackTrace()
// Print trace information: class name, method name, file
name, and line number.
java.lang.ArithmeticException: /by zero
at MyClass,divide(MyClass.java:5)
Open File Example, cont.
try {
File fd = new File(filename);
processFile(fd);
fd.close()
}
catch (FileNotFound e) {
System.out.println(“Cannot find file”+e);
e.printStackTrace();
}
catch (FileOpenFailed e) {
System.out.println(“Cannot open file”+e);
e.printStackTrace();
}
Claiming, Throwing, and
Catching Exceptions
method1()
{
try
{
invoke method2;
}
catch (Exception ex)
{
Process exception;
}
catch exception
}
method2() throws Exception
{
if (an error occurs)
{
throw new Exception();
}
}
claim exception
throw exception
Rethrowing Exceptions
try
{
statements;
}
catch(TheException e)
{
perform operations before exits;
throw e;
}
Catching Exceptions
main method
{
...
try
{
...
invoke method1;
statement1;
}
catch (Exception1 ex1)
{
Process ex1;
}
method1
{
...
try
{
...
invoke method2;
statement2;
}
catch (Exception2 ex2)
{
Process ex2;
}
method2
{
...
try
{
...
invoke method3;
statement3;
}
catch (Exception3 ex3)
{
Process ex3;
}
}
}
}
The finally Clause
You may want some code to be executed regardless of
whether an exception occurs or is caught. Java has a finally
clause that can accomplish this objective.
try
{
statements;
}
catch(TheException1 e)
{
handling e;
}
catch(TheException2 e)
{
handling e;
}
finally
{
finalStatements;
}
The finally Clause
If no exception arises in the try block, finalStatement is
executed.
If one of the statements causes an exception in try block that
is caught in a catch clause, the other statements in try block
are skipped, the catch clause is executed, and the finally
clause is executed.
* If the catch clause does not rethrow an exception, the next
statement is executed.
* If it does, the exception is passed to the caller of the method.
If one of the statements causes an exception is not caught in
any catch clause, the other statements in the try block are
skipped, the finally clause is executed, and the exception is
passed to the caller of this method.
Example: finally
Suppose that statement2 causes an exception ex2:
try
{
statement1;
statement2;
statement3;
}
catch(TheException1 ex1) {
catch(TheException2 ex2) {
finally
{
statement 4;
Output:
statement1;
finalStatement;
statement4;
handling ex1;
}
handling ex2;
}
finalStatement; }
Cautions When Using Exceptions
Exception handling separates error-handling code from
normal programming tasks, thus making programs
easier to read and to modify.
Be aware, however, that exception handling usually
requires more time and resources because it requires
instantiating a new exception object, rolling back the
call stack, and propagating the errors to the calling
methods.
Exceptions and Exception Types
ClassNotFoundException
IOException
ArithmeticException
Exception
AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object
Throwable
Several more classes
Several more classes
LinkageError
VirtualMachineError
Error
AWTError
Several more classes