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

Chapter06 - Exception Handling

This document discusses exception handling in Java. It begins by defining exceptions as errors that occur during program execution. Exceptions are classified as either compile-time or runtime exceptions. The document then covers the exception hierarchy in Java, with Throwable at the top and Exception and Error as main sub-classes. It describes checked and unchecked exceptions, and provides examples of common exceptions in each category. Finally, it explains how to handle exceptions using try, catch, and finally blocks, and how to throw exceptions explicitly in code using the throw keyword.

Uploaded by

Seyo Kasaye
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Chapter06 - Exception Handling

This document discusses exception handling in Java. It begins by defining exceptions as errors that occur during program execution. Exceptions are classified as either compile-time or runtime exceptions. The document then covers the exception hierarchy in Java, with Throwable at the top and Exception and Error as main sub-classes. It describes checked and unchecked exceptions, and provides examples of common exceptions in each category. Finally, it explains how to handle exceptions using try, catch, and finally blocks, and how to throw exceptions explicitly in code using the throw keyword.

Uploaded by

Seyo Kasaye
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Object Oriented Programming (SE 2031)

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.
 Exception may occur at compile time or at runtime.
 Exceptions which occur at compile time are called
Checked exceptions.
 Ex: 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) user-defined exception classes
2. Error – exceptions used by Java to indicate errors with the runtime
environment; user programs are not supposed to catch them

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


Some Common Checked Exceptions
declared in throws clause.
1. NoSuchMethodException
 If not caught or declared, compiler error occurs.
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 caught 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
Some Common Unchecked Exceptions
1. Can typically be
ArithmaticException prevented
(Divide By 0) by properAllcoding
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("c="+c);
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 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 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:

public static void main(String args[]) {


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

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

static void procB()


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

27
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");
}
}

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:

class MyException extends Exception


{
………
}
 MyException need not implement anything – its

mere existence in the type system allows to use its


objects as exceptions.
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:
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}

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:
{ Called compute(1)
Normal exit
compute(1); Called compute(20)
compute(20); Caught MyException[20]
}
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
32
}
Self -Review Questions

1. What is a package? How do we design a package?


2. How do we add a class or interface to a package?
3. Explain in detail about accessing a package.
4. Explain about the access protection in packages?
5. What is interface? Write a program to demonstrate how
interfaces can be extended.
6. Does Java Support multiple inheritance? Write Java a program
to implement the multilevel Inheritance.

33

You might also like