You are on page 1of 11

CSCI03

HANDLING EXCEPTIONS AND EVENTS

EXCEPTION
Occurrence of an undesirable situation that can be detected during program execution. Example:
Division by zero Entering invalid data

If exceptions occurred during the program execution, the program terminated with an appropriate error message.

HANDLING EXCEPTIONS WITHIN A PROGRAM


The following shows what happen when division by zero is attempted or an invalid input occurs and the problem is not addresses:

HANDLING EXCEPTIONS WITHIN A PROGRAM


Sample Run 1

Sample Run 2

JAVAS MECHANISM OF EXCEPTION HANDLING


SYNTAX: try{ . }catch(ExceptionClassName obj){ . }finally{ . }

JAVAS MECHANISM OF EXCEPTION HANDLING


try block
Contains statements that might generate an exception. It also contains statements which should not be executed when an exception occur. Each java program can only have one try block.

catch block
Specifies the type of exceptions it can catch and contains an exception handler. A java program can have more than one catch block and can either be followed by a finally block.

finally block
It is always being executed whether or not an exception occur.

JAVAS MECHANISM OF EXCEPTION HANDLING

JAVAS MECHANISM OF EXCEPTION HANDLING


Sample Run 1

Sample Run 2

Sample Run 3

JAVA EXCEPTION CLASSES


Class Exception
It is the superclass of the classes that handles exception. Examples:
IOException, InputMismatchException, NumberFormatException, FileNotFoundException, ArrayIndexOutOfBoundsException, etc.

These exceptions are typically found in java.lang package.

JAVA EXCEPTION CLASSES


Exception Classes ArithmeticException ArrayIndexOutOfBoundsException Description Arithmetic Errors such as division by zero Array is either less than 0 or greater than or equal to the length of the array Reference to a file cannot be found Use of an Illegal number format Input retrieved does not match the pattern for the expected type or the token is out of range for the expected type

FileNotFoundException NumberFormatException InputMismatchException

You might also like