0% found this document useful (0 votes)
19 views27 pages

OOP Chapter 4

This document discusses exception handling in object-oriented programming. It defines an exception as an event that disrupts normal program flow, such as division by zero or an out-of-bounds array access. Exception handling uses try, catch, and finally blocks to monitor code for exceptions, catch specific exception types, and ensure cleanup code is always executed. There are two types of exceptions: unchecked exceptions for programming errors and checked exceptions for external errors that must be caught or declared. Finally blocks are used to execute cleanup code regardless of exceptions.

Uploaded by

mesfin snow
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views27 pages

OOP Chapter 4

This document discusses exception handling in object-oriented programming. It defines an exception as an event that disrupts normal program flow, such as division by zero or an out-of-bounds array access. Exception handling uses try, catch, and finally blocks to monitor code for exceptions, catch specific exception types, and ensure cleanup code is always executed. There are two types of exceptions: unchecked exceptions for programming errors and checked exceptions for external errors that must be caught or declared. Finally blocks are used to execute cleanup code regardless of exceptions.

Uploaded by

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

1

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

All of these problems have to be handled using

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

Throwable class (which is the base class for all exceptions)


 Exceptions can be:

1. generated by the Java run-time system Fundamental errors

that violate the rules of the Java language or the constraints


of the Java execution environment.

2. manually generated by programmer’s code Such


exceptions are typically used to report some error
conditions to the caller of a method.
6
Exception Constructs
 Five constructs are used in exception handling:

A. try – a block surrounding program statements to monitor


for exceptions
B. catch – together with try, catches specific kinds of
exceptions and handles them in some way
C. finally – specifies any code that absolutely must be
executed whether or not an exception occurs
D. throw – used to throw a specific exception from the
program
E. throws – specifies which exceptions a given method can
7
throw
Exception-Handling Block
 General form:
try { … }
catch(Exception1 ex1) { … }
catch(Exception2 ex2) { … }

finally { … }
where:
1) try { … } is the block of code to monitor for exceptions
2) catch(Exception ex) { … } is exception handler for the
exception Exception
3) finally { … } is the block of code to execute before the try
8
block ends
Another Exception Example
What is the output of this program?

public class Unchecked_Demo {


public static void main(String args[]){
int num []={1,2,3,4};
System .out.println(num [5]);
}
}

Output:Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Dem o.java:8))

9
Exception Types
 There are two types of Exceptions:

A. Built-in Exceptions: are exceptions which are handled by


the java compiler.
i. Checked Exceptions: A checked exception is an exception that
occurs at the compile time, these are also called as compile time
exceptions.
ii. Unchecked Exceptions: An unchecked exception is an exception
that occurs at the time of execution. These are also called as
Runtime Exceptions. These include programming bugs, such
as logic errors. Runtime exceptions are ignored at the time
of compilation.
B. User-defined Exceptions: are exceptions types created by

10
the user program.
Exception Class Hierarchy
Exception

RuntimeException IOException SQLException

ArrayIndexOutofBounds FileNotFoundException

NullPointerException MalformedURLException

IllegalArgumentException SocketException

etc. etc.

Unchecked Exceptions Checked Exceptions


11
Unchecked Exceptions
 The compiler does not check if a method handles or throws there
exceptions
 Usually occur because of programming errors, when code is not robust
enough to prevent them
 They are numerous and can be ignored by the programmer
 Some of the common unchecked exceptions include:
1. ArithmeticException
2. ArrayIndexOutOfBoundsException
3. ArrayStoreException
4. ClassCastException
5. IllegalStateException
6. IllegalMonitorStateException
7. IllegalArgumentException

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

not subclass of subclass of


RuntimeException RuntimeException
if not caught, method must if not caught, method may
specify it to be thrown specify it to be thrown
for errors that the for errors that the
programmer cannot directly programmer can directly
prevent from occurring prevent from occurring,
IOException, NullPointerException,
FileNotFoundException, IllegalArgumentException,
SocketException IllegalStateException
15
Exception Handling
Use a try-catch block to handle exceptions that are
thrown

try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}

16
Exception Handling Example

public static int average(int[] a) {


int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}

public static void printAverage(int[] a) {


try {
int avg = average(a);
System.out.println("the average is: " + avg);
}
catch (ArithmeticException e) {
System.out.println("error calculating average");
}
}
17
Catching Multiple Exceptions
 Handle multiple possible exceptions by multiple successive catch
blocks

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

2. single String argument descriptive message that appears


when exception error message is printed
IllegalArgumentExceptione e =
new IllegalArgumentException("number must be
positive");

19
finally
 When an exception is thrown:

1) the execution of a method is changed


2) the method may even return prematurely.
 This problem may be 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.
 It will be executed whether an exception is thrown or not.
 If we don’t provide catch block for all the exceptions, while
using try …catch, we can write the message in finally block so
20 that there will not be an error.
Contd.
 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.

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:

static void procB() {


try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
23
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");
}
}

24
Creating Own Exception Classes
 Build-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.
25
class MyException extends Exception {
private int Age;
MyException(int a) {
Age = a;
}
public String toString() {
return "MyException[" + Age + "] \nAge should not be Negative";
}
}
public class ExceptionDemo {
public static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if (a<=0) throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(-20);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}}
26 }
27
???
06/09/23

You might also like