OOP Chapter 4
OOP Chapter 4
METTU UNIVERSITY
COLLEGE OF ENGINEERING AND
TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE
Object-oriented programming
by Baharudin Sh.
Chapter Four
Exception-Handling
2
What is an Exception?
Is an event which occurs during the execution of a
program, that disrupts the normal program flow and may
cause a program to fail.
Some examples:
Performing illegal arithmetic (division by zero)
Illegal arguments to methods
Accessing an out-of-bounds array element
Hardware failures
Writing to a read-only file
Opening a non-existing file
3
exception handling.
Contd.
An exception is an object that describes an exceptional
condition (error) that has occurred when executing a
program.
4
1 // Example DivideByZeroNoExceptionHandling.java
2 // An application that attempts to divide by zero.
3 import java.util.Scanner;
4 Example of Exception
5 public class DivideByZeroNoExceptionHandling
6 {
7 // demonstrates throwing an exception when a divide-by-zero occurs
8 public static int divided( int divident, int divisor )
9 {
10 return divident / divisor; // possible division by zero
11 } // end method quotient
12
13 public static void main( String args[] )
14 {
15 Scanner scanner = new Scanner( System.in ); // scanner for input
16
17 System.out.print( "Please enter an integer divident: " );
18 int divident= scanner.nextInt();
19 System.out.print( "Please enter an integer divisor: " );
20 int divisor = scanner.nextInt();
21
22 int result = divided( divident, divisor );
23 System.out.printf(
24 "\nResult: %d / %d = %d\n", divident, divisor, result );
5 25 } // end main
26 } // end class DivideByZeroNoExceptionHandling
Exception Sources
All exceptions are instances of a class extended from
9
Exception Types
There are two types of Exceptions:
10
the user program.
Exception Class Hierarchy
Exception
ArrayIndexOutofBounds FileNotFoundException
NullPointerException MalformedURLException
IllegalArgumentException SocketException
etc. etc.
12
Checked Exceptions
These exceptions must be included in the method’s throws
clause if the method generates but does not handle them
Usually occur because of errors programmer cannot control:
examples: hardware failures, unreadable files
They are less frequent and they cannot be ignored by the
programmer .
Some of the checked exceptions are:
1. NoSuchMethodException NoSuchFieldException
2. InterruptedException
3. InstantiationException
4. IllegalAccessException
5. CloneNotSupportedException
6. ClassNotFoundException
13
Dealing With Checked Exceptions
Every method must catch (handle) checked
exceptions or specify that it may throw them
Specify with the throws keyword
void readFile(String filename) {
try {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
} catch (FileNotFoundException e) {
System.out.println("file was not found");
}
} or
void readFile(String filename) throws FileNotFoundException
{FileReader reader = new FileReader("myfile.txt");
// read from file . . .
}
14
Checked and Unchecked Exceptions
Checked Exception Unchecked Exception
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
16
Exception Handling Example
try {
// code that might throw multiple
exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
18
}
Exception Constructors
Exceptions have at least two constructors:
1. no arguments
NullPointerException e = new NullPointerException();
19
finally
When an exception is thrown:
1) uncaught exception or
2) explicit return
the finally clause is executed just before the method returns.
21
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");
}}
22
Example: finally 2
// procB’s try statement is exited via a return statement, the
finally clause is executed before procB returns:
24
Creating Own Exception Classes
Build-in exception classes handle some generic errors.
classes. How?
Define a subclass of Exception: