6.0_ExceptionHandling_v3.0

Download Report

Transcript 6.0_ExceptionHandling_v3.0

Exception Handling in Java
6.0 Exception Handling
Introduction:
After completing this chapter, you will be able to comprehend the natu
and kinds of exceptions in java and to handle exceptions in in an
efficient manner.
Objective:
After completing this chapter, you will able to,
Use exception Handling Hierarchy
Explain kinds and nature of Exceptions
Differentiate between Throw and Throws
Use methods for Handling Exceptions
Print Stack Traces
Rethrow Exceptions
2
Introduction
• Exception Handling :
– Is a mechanism that allows Java programs to handle various exceptional
conditions.
– Exception - condition which occurs during program execution which is (usually)
indicative of some kind of failure or error condition.
– A program can throw an exception explicitly using the throw statement.
– After an exception is thrown - control is transferred from the current point of
execution to an appropriate catch clause of an enclosing try statement
– Catch clause - is the exception handler.
– E.g:
» attempting to access a file which does not exist,
» attempting to convert a non-numeric string to a numeric value etc..
3
Introduction
• E.g. :
try {
out.write(b);
} catch (IOException e) {
System.out.println("Output Error");
} finally {
out.close();
}
•
The Finally Block - always executed before control leaves the try statement
•
If the Try clause does not have any catch clause to handle the exception
» it propagates up through enclosing statements in the
current method
Invoking method
..goes on till it finds the catch clause to handle the exception,
else the thread terminates.
•
The parameter in a catch clause must be of type Throwable or one of its subclasses
4
Exception Handling Hierarchy
5
Kinds of Exceptions
• Java has two kinds of exceptions:
– unchecked exception - NOT required to provide code to
handle it.
– checked exception - MUST provide code to handle or a fatal
compiler error will be issued.
– If the programmer calls a method which can throw a checked
exception, code must be provided to handle that exception
6
Nature of Exceptions
•
Broadly speaking, there are three different situations that cause exceptions
to be thrown:
– Exceptions due to programming errors:
• e.g., NullPointerException and IllegalArgumentException).
– Exceptions due to client code errors:
• Client code attempts something not allowed by the API, and thereby violates its
contract.
•
The client can take some alternative course of action, if there is useful information
provided in the exception.
– Exceptions due to resource failures:
• For example: the system runs out of memory or a network connection fails.
7
Throw and Throws
• ‘throw’ keyword is used to throw the exceptions explicitly.
– Syntax for throw:
throw ThrowableInstance;
• ‘throws’ keyword lists the type of exceptions that a method might throw.
– Syntax for throws:
type method-name(parameter-list) throws exception-list
{
//body of method
}
8
Throw and Throws
• E.g. for Throw :
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException(“demo”);
} catch (NullPointerException e) {
System.out.printl(“caught in demoproc”);
throw e;
}
}
public static void main (String args[]) {
try {
demoproc();
} catch (NullPointerException e) {
System.out.println(“recaught:” + e);
}
}
}
9
Throw and Throws
•E.g. for Throws :
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println(“Inside throwOne.”);
throw new IllegalAccessException(“demo”);
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println(“Caught” + e);
}
}
}
1 0
Methods for Handling Exceptions
• Various methods for handling exceptions :
– Declaring exceptions :
• If a method is expected to throw any exceptions, the method
declaration must declare that fact in a throws clause.
• The classes listed in a throws clause must be Throwable or any
of its subclasses;
• The Throwable class is the superclass of all objects that can be
thrown in Java.
• If the exception is an instance of Error, RunTimeException, or a
subclass of one of those classes, it does not have to be listed in
a throws clause.
1 1
Methods for Handling Exceptions
•
E.g.:
class throwsExample {
...
// Method explicitly throws an exception
int read() throws IOException {
if (….) throw new IOException();
return … ;
}
// Method implicitly throws an exception
String readUpTo(….) throws IOException {
int c = read();
// Can throw IOException
return …. ;
}
1 2
Methods for Handling Exceptions
// Method catches an exception internally
getLength() {
….
try {
s = readUpTo(':');
} catch (IOException e) {
……
}
}
// Method can throw a RunTimeException
getAvgLength() {
…….
return total/count;
// Can throw ArithmeticException
}}
1 3
Methods for Handling Exceptions
•
Generating Exceptions :
• For program-defined exceptions:
» define a new subclass of Exception that is specific to your program.
E.g.:
class WrongDayException extends Exception {
public WrongDayException () {}
public WrongDayException(String msg) {
super(msg);
}}
public class ThrowExample {
void doIt() throws WrongDayException{
…….
} public static void main (String [] argv) {
try {
……..
} catch (WrongDayException e) {
…..
}
}}
1 4
Printing Stack Traces
•
Printing Stack Traces:
• To figure out where the exception came from.
• A stack trace looks like the following:
java.lang.ArithmeticException: / by zero
at t.cap(t.java:16) at t.doit(t.java:8) at t.main(t.java:3)
• printStackTrace() method - prints the stack trace.
• E.g.:
int cap (x) {
return 100/x
} try {
cap(0);
} catch(ArithmeticException e) {
e.printStackTrace();
}
1 5
Rethrowing Exceptions
•
Rethrowing Exceptions :
•
E.g. :
try {
cap(0);
} catch(ArithmeticException e) {
throw e;
}
•
The above code rethrows an exception and has the stack trace indicate the original location
•
fillInStackTrace() method - sets the stack trace information in the exception based on the current
execution context.
•
E.g. :
try {
cap(0);
} catch(ArithmeticException e) {
throw (ArithmeticException)e.fillInStackTrace();
}
1 6
Exception Handling - Summary
•
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions.
•
Two kinds of Exception :
• Checked Exception
• UnChecked Exception
•
An exception causes a jump to the end of try block. If the exception occurred in a method
called from a try block, the called method is abandoned.
•
If there’s a catch block for the occurred exception or a parent class of the exception, the
exception is now considered handled.
•
At least one ‘catch’ block or one ‘finally’ block must accompany a ‘try’ statement. If all 3
blocks are present, the order is important. (try/catch/finally)
•
finally and catch can come only with try, they cannot appear on their own.
•
Regardless of whether or not an exception occurred or whether or not it was handled, if
there is a finally block, it’ll be executed always. (Even if there is a return statement in try
block).
1 7
Exception Handling - Summary
• If the exception is not handled, the process repeats looking for next
enclosing try block up the call hierarchy. If this search reaches the top
level of the hierarchy (the point at which the thread wascreated), then
the thread is killed and message stack trace is dumped to System.err.
•The method fillInStackTrace() in Throwable class throws a Throwable
object. It will be useful when re-throwing an exception or error.
1 8
Test Your Understanding
• What is an Exception?
• What is the difference between Throw and Throws?
• What happens when an exception is not handled?
• What is a checked exception?
• What is necessity to re-throw an exception?
1 9