CS202 - Chapter 2 - Exceptions
CS202 - Chapter 2 - Exceptions
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.
Examples
Division by zero
Thus, the method engendering an exception does not return a result but emits an exception
and explains the cause.
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.
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.
We remark that only the error detection was formulated in the previous
example without its handling.
For each case, the treatment is to display a message about the encountered
exception.
These exceptions
should be catched
and handled
(try/catch) or the
calling method should
handle it by using
(throws)