0% found this document useful (0 votes)
35 views

Chapter 4 Exception Handling

Uploaded by

sisay alemu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Chapter 4 Exception Handling

Uploaded by

sisay alemu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Chapter 4

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 be 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.
 Exception may occur at compile time or at runtime.
 Exceptions which occur at compile time are called
Checked exceptions.
 Example: ClassNotFoundException,
NoSuchMethodException, NoSuchFieldException etc.
 Exceptions which occur at run time are called
Unchecked exceptions. 4
Exception Hierarchy
 All exceptions are sub-classes of the built-in class
Throwable.
 Throwable contains two immediate sub-classes:
1. Exception – exceptional conditions that programs should
catch. The class includes:
a) RuntimeException – defined automatically for user
programs to include: division by zero, invalid array
indexing, etc.
b) use-defined exception classes
2. Error – exceptions used by Java to indicate errors with the
runtime environment; user programs are not supposed to catch 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.


 Some
If Common Checked Exceptions
not caught or declared, compiler error occurs.
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));
}
}

Expdemo.java:9: unreported exception java.io.IOException; must be caught or declared to be


thrown
int a = Integer.parseInt(br.readLine());
Expdemo3.java:10: unreported exception java.io.IOException; must be caugh or declared to be
thrown
int b = Integer.parseInt(br.readLine()); 8
Unchecked Exceptions
 Inherit from class RuntimeException or class Error
 Compiler does not check code to see if exception
caught or declared
 If an unchecked exception occurs and not caught
 Program terminates or runs with unexpected results
 Can typically be prevented by proper coding23
Some Common Unchecked Exceptions
1. ArithmaticException (Divide By 0) All Unchecked Exceptions
directly or indirectly are sub
2. ArrayIndexOutOfBoundsException
classes of
3. ArrayStoreException RunTimeException
4. FileNotFoundException
5. NullPointerException
6. NumberFormatException
7. IllegalArumentsException

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(“x="+x);
Unchecked Exceptions
int y = a/(b+c);
System.out.println("y="+y);
} Can Throw an Exception
}

C:\>javac Exceptiondemo1.java << Compilation Step Pass>>


C:\>java Exceptiondemo1
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at Exceptiondemo1.main(Exceptiondemo1.java:8) 10
Exception Handling
 Code that could generate errors put in try blocks
 Code for error handling enclosed in a catch clause
 The finally clause always executes
 Five constructs are used in exception handling:
1. try – a block surrounding program statements to monitor for
exceptions
2. catch – together with try, catches specific kinds of exceptions
and handles them in some way
3. finally – specifies any code that absolutely must be executed
whether or not an exception occurs
4. throw – used to throw a specific exception from the program
5. throws – specifies which exceptions a given method can throw

11
Exception Handler
The
Thestatement
statementthat
thatcauses
causesan
anexception
exceptionisis
try block thrown
thrownfrom
fromhere
here

The
Thestatement
statementthat
thathandles
handlesthe
theexception
exception
catch block

Figure: Exception Handling mechanism

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
catch(Exception2 e2){ monitor for exceptions

} 2. catch(Exception ex) { … } is exception
finally { handler for the exception Arithmetic

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());
}
finally
{
System.out.println(“Quit\n”); Output:
} Error: / by zero
}
Quit
}
14
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 15
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) {
……
}

16
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;
}
}

17
Example: throw 2
/*The main method calls demoproc within the try block which
catches and handles the NullPointerException exception*/

public static void main(String args[]) {


try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}

18
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.

19
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();
}
} 20
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);
}
}
}

21
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.

22
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.
23
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");
}
}

24
Example: finally 2
// procB’s try statement is exited via a return statement, the finally clause is
executed before procB returns:

static void procB()


{
try
{ System.out.println("inside procB");
return;
}
finally
{ System.out.println("procB's finally");
}
}

25
Example: finally 3
 In procC, the try statement executes normally without error, however the
finally clause is still executed:

static void procC()


{
try
{
System.out.println("inside procC");
}
finally
{
System.out.println("procC's finally");
}
}

26
E ND
T he
u ! ! !
Yo
T ha nk
27

You might also like