Chapter06 - Exception Handling
Chapter06 - Exception Handling
Chapter 06
Exception Handling
1
Objectives
After studying this chapter, students should be able to learn:
Exception
Exception Hierarchy
Exception Handling
Throwing Exception
User-defined Exceptions
2
Introduction
An error in a program is called bug. Removing errors from
program is called debugging.
Errors are broadly classified into 2 types:
Compile-time Errors:
Errors which occur due to syntax or format is called compile time errors.
These errors are detected by java compiler at compilation time.
The .class file will not be created due to errors.
Most of the compile-time errors are due to typing mistakes.
Examples: missing semicolon, missing double quotes, use of undeclared
variables etc.
Run-time Errors:
These are the errors that represent computer inefficiency.
Insufficient memory to store data or inability of the microprocessor to
execute some statement is examples to runtime errors.
Runtime errors are detected by JVM at runtime.
Examples: division by zero, accessing an element that is out of the array
bound, converting invalid strings to integer etc. 3
Exception
An abnormal event in a program is called an Exception.
5
Hierarchy of Exception Classes
6
Checked Exceptions
Inherit from class Exception but not from RuntimeException
Compiler enforces catch-or-declare requirement
Compiler checks each method call and method declaration
determines whether method throws checked exceptions.
If so, the compiler ensures checked exception caught or declared in
throws clause.
If not caught or declared, compiler error occurs.
Some Common Checked Exceptions
1. NoSuchMethodException
2. NoSuchFieldException
3. InterruptedException
4. InstantiationException
5. IllegalAccessException
6. CloneNotSupportedException
7. ClassNotFoundException
7
Checked Exceptions
/* Program to read two integers and Display their sum */
import java.io.*;
class Expdemo
{
public static void main(String args[])
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
System.out.println("Sum is :"+(a+b));
}
}
9
UncheckedExceptions Example
class Exceptiondemo1
{
public static void main(String args[]) throws ArithmeticException
{
int a=10;
int b= 5;
int c =5;
int x = a/(b-c); // Dynamic Initilization
No Need to mention for
System.out.println("c="+c);
Unchecked Exceptions
int y = a/(b+c);
System.out.println("y="+y);
} Can Throw an Exception
}
11
Exception Handler
The statement that causes an exception is
try block thrown from here
12
Exception Handling Blocks
General form:
try {
… // generates an exception
}
catch(Exception1 e1){
where:
…//handles the exception
} 1. try { … } is the block of code to monitor
catch(Exception2 e2){ for exceptions
…
} 2. catch(Exception ex) { … } is exception
finally { handler for the exception Exception
…
3. finally { … } is the block of code to
}
execute before the try block ends
13
Example
class DivByZero
{
public static void main(String args[])
{
try {
int a = 10, b = 0, c;
c = a / b;
System.out.println("Division = " + c);
}catch (ArithmeticException e) {
System.out.println("Error:" + e.getMessage());
}
}
}
}
Output:
Error: / by zero
Quit
14
Example - Multiple catch
Statements
class MultipleCatch {
public static void main(String args[]) {
try {
int a = 10, b = 0, c;
c = a / b;
System.out.println("Division = " + c);
int x[] = {1, 2, 3};
x[30] = 100;
} catch (ArithmeticException e) {
System.out.println("Error:" + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e2) {
System.out.println("Error:" + e2.toString());
}
}
} Even though multiple exceptions are found in the program,
only one exception is raised at a time.
15
Nested try's
class NestedTryDemo {
public static void main(String args[]){
try {
int a = Integer.parseInt(args[0]);
try {
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println(“Div by zero error!");
}
}
catch (ArrayIndexOutOfBoundsException) {
System.out.println(“Need 2 parameters!");
}
}
}
16
Throwing Exceptions(throw)
So far, we were only catching the exceptions thrown by the
Java system.
In fact, a user program may throw an exception explicitly:
throw ThrowableInstance;
ThrowableInstance must be an object of type Throwable or its subclass.
Once an exception is thrown by: throw ThrowableInstance;
1. the flow of control stops immediately
2. the nearest enclosing try statement is inspected if it has a catch
statement that matches the type of exception:
3. if one exists, control is transferred to that statement
4. otherwise, the next enclosing try statement is examined
5. if no enclosing try statement has a corresponding catch clause, the
default exception handler halts the program and prints the stack
17
Contd.
Two ways to obtain a Throwable instance:
1. creating one with the new operator
All Java built-in exceptions have at least two constructors:
One without parameters and another with one String parameter:
throw new NullPointerException("demo");
2. using a parameter of the catch clause
try { …
}
catch(Throwable e) {
……
}
18
Example: throw 1
class ThrowDemo {
//The method demoproc throws a NullPointerException
//exception which is immediately caught in the try block and re-thrown:
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e;
}
}
19
Example: throw 2
//The main method calls demoproc within the try block which
catches and handles the NullPointerException exception:
20
throws Declaration
If a method is capable of causing an exception that it does
not handle, it must specify this behavior by the throws
clause in its declaration:
type name(parameter-list) throws exception-list {
…
}
where exception-list is a comma-separated list of all types
of exceptions that a method might throw.
All exceptions must be listed except Error and
RuntimeException or any of their subclasses, otherwise a
compile-time error occurs.
21
Example: throws 1
The throwOne method throws an exception that it does not
catch, nor declares it within the throws clause.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
Therefore this program does not compile.
22
Example: throws 2
Corrected program: throwOne lists exception, main catches it:
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);
}
}
}
23
finally
When an exception is thrown:
1) the execution of a method is changed
2) the method may even return prematurely.
This may be a problem in many situations.
For instance, if a method opens a file on entry and closes
on exit; exception handling should not bypass the proper
closure of the file.
The finally block is used to address this problem.
24
finally Clause
The try/catch statement requires at least one catch or finally
clause, although both are optional:
try { …
}
catch(Exception1 ex1) {
… }
…
finally { …
}
Executed after try/catch whether or not the exception is thrown.
Any time a method is to return to a caller from inside the
try/catch block via:
1) uncaught exception or
2) explicit return the finally clause is executed just before the method
returns.
25
Example: finally 1
Three methods to exit in various ways.
class FinallyDemo {
//procA prematurely breaks out of the try by throwing an exception, the finally
clause is executed on the way out:
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
26
Example: finally 2
// procB’s try statement is exited via a return statement, the finally clause is
executed before procB returns:
27
Example: finally 3
In procC, the try statement executes normally without error, however the
finally clause is still executed:
28
Creating Own Exception Classes
Built-in exception classes handle some generic errors.
For application-specific errors, define your own exception
classes. How?
Define a subclass of Exception:
29
Example: Own Exceptions 1
A new exception class is defined, with a private detail
variable, a one parameter constructor and an overridden
toString method:
30
Example: Own Exceptions 2
class ExceptionDemo
{
//The static compute method throws the MyException exception whenever
its a argument is greater than 10:
static void compute(int a) throws MyException
{
System.out.println("Called compute: " + a);
if (a > 10) throw new MyException(a);
System.out.println("Normal exit");
}
31
Example: Own Exceptions 3
The main method calls compute with two arguments within a
try block that catches the MyException exception:
public static void main(String args[])
{
try
{
Output:
compute(1); Called compute(1)
compute(20); Normal exit
} Called compute(20)
Caught MyException[20]
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}
32