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

CS202 - Chapter 2 - Exceptions

Uploaded by

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

CS202 - Chapter 2 - Exceptions

Uploaded by

Imy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CS202 ADVANCED OBJECT-ORIENTED PROGRAMMING

CHAPTER 2

EXCEPTIONS

1/15/2024 1
Introduction
In programming, it is crucial to consider all eventual errors.

To make a program robust, all the possible errors have to be detected and handled.

Any program may face an exceptional condition (or exception) during its execution.

There are some programming languages (ex Java) proposing a mechanism of error handling
based on the exception notion.

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 2


What is an exception?
An exception is a situation that stops the normal execution of a program (not a bug)

Examples

an inexistant file which is necssary for the execution of the problem.

Division by zero

Exceeding the bounds of a table

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 3


Exception: Definition
An exception is an object that may be issued by a method if an execptional event occurs
(including the errors).

Thus, the method engendering an exception does not return a result but emits an exception
and explains the cause.

The propagation of an exception emission follows the next steps:

1. An exception is generated inside a method

2. If the method has a treatment for this exception, we go to step 4, otherwse we go to step 3

3. The exception test is returned to the method calling the current method (which emits the
exception), we go to step 2

4. The exception is handled and the execution of the program will continuate normally.

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 4


Exceptions handling
The exception is spread from where it is thrown, it goes back from caller to
caller and stops at every encountered exception handler.
Each exception handler is reviewed, starting from the first that is declared.
If this exception handler is compatible with the exception type, the
associated code then the recovery associated code will be executed and
then the program takes back normally its execution just after the last
exception handler.
If there is no suitable exception handler, the same process is reiterated by
going up, until an exception handler captures it or the main function is
reached.

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 5


Advantages of exceptions handling
Easy programming and readability
It is possible to group the error management at the same level in order to avoid redundancies
of code handling errors.
A clean and explicit error management
some programming languages use the return value of methods to report an error to the calling
method. Since it is not the role of the return value to describe an error. Disassociating the return
value and the exception allows the exception to accurately describe the line of code that
caused the error and the nature of the error.

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 6


Exception declaration
It is necessary to declare for each method, the exception classes that can be eventually
emitted.

This declaration is done at the end of the signature thanks to the keyword throws.

Exemple
public static int parseInt(String s) throws NumberFormatException { ...
}
This method converts a string (containg only numbers) to an int.

An error occurs when this string contains other types of characters. In this case an exception
NumberFormatException will be emitted.

1/15/2024 ADVANCED OBJECT-ORIENTED PROGRAMMING 7


Declaration – raise an exception

An exception may be emitted in/by a method

• By another method called inside the first one

• By creating an object which instantiates the class Exception (class


Throwable) or explicitely by the keyword throw.

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 8


Example
public class ExampleException {
/* This method returns the month according to the number provided as a parameter. If this number is
invalid (does not belong to [1, 12], an exception of type IndexOutOfBoundsException will be emitted.
*/

public static String month(int month) throws IndexOutOfBoundsException {


if ((month < 1) || (month > 12)) {
throw new IndexOutOfBoundsException( ”the month number ” + month + ” should be
between 1 and 12”); }
if (month == 1)
return ”January”;
else if (month == 2)
return ”February”;
...
else if (month == 11)
return ”November”;
else
return ”December”;}
}

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 9


The exception IndexOutOfBoundsException means that the provided index
exceeds the maximum and minimum prefixed (between 1 and 12 for this
example).

We remark that only the error detection was formulated in the previous
example without its handling.

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 10


Interception et treatement of an exception
public class TreatementExceptionExample {
public static void main(String[] args) {
System.out.print(”please input the month number : ”);
try {
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
String choice = input.readLine();
int number = Integer.parseInt(choice);
System.out.println(ExampleException.month(number));
} catch (IndexOutOfBoundsException e) {
System.err.println(”incorrect number: ” + e.getMessage());}
catch (NumberFormatException e) {
System.err.println(”incorrect input: ” + e.getMessage()); }
catch (IOException e) {
System.err.println(”access error: ” + e.getMessage()); }
// we catch multiple types of exceptions here
}
}

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 11


Three classes of exceptions are handled in this example:

➢ IndexOutOfBoundsException (emitted by the method month) occurs


when the number is <1 or >12

➢ NumberFormatException (emitted by the method parseInt) occurs


when the text given by the user cannot be converted to int

➢ IOException (emitted by the method readLine) occurs when there is an


access error in input devices.

For each case, the treatment is to display a message about the encountered
exception.

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 12


Exceptions hierarchy
The super class of the exceptions.

These exceptions
should be catched
and handled
(try/catch) or the
calling method should
handle it by using
(throws)

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 13


Frequent Exception classes (some examples)
Class Description
AWTException Graphical Operations
ClassCastException Error of incompatibility in converting an object
FileNotFoundException attempt to open a non-existent file
IndexOutOfBoundsException Error in the access to an element in a set
IOException Input/output operations
A null pointer null is received by a method not accepting
NullPointerException this value, or when calling a method or a variable from a
pointer (length or access to a null box of a table, ...)
ArrayIndexOutOfBoundsException Access to a non-existent box in the table
StringIndexOutOfBoundsException Access to a non-existant character of a string
NegativeArraySizeException negative size of a table
NumberFormatException Error in converting a string to a number

1/15/2024 ADVANCED OBJECT ORIENTED PROGRAMMING 14

You might also like