Page 250 - IT-802_class_12
P. 250
Notes
If the method divide() had used floating point numbers instead of integers, there would not have been
an error, since in floating-point arithmetic, division by zero is allowed — it results in infinity, which
would be displayed as Infinity. Java provides an exception handling mechanism so that a program is
able to deal with exceptions, and continue executing or terminate gracefully.
The basic idea in exception handling is to:
Ð ÐDenote an exception block: Identify areas in the code where errors can occur.
Ð ÐCatch the exception: Receive the error information.
Ð ÐHandle the exception: Take corrective action to recover from the error.
Java provides the following keywords to handle an exception:
Ð Ðtry: A try block surrounds the part of the code that can generate exception(s).
Ð Ðcatch: The catch blocks follow a try block. A catch block contains the exception handler - specific code that is executed
when the exception occurs. Multiple catch blocks following a try block can handle different types of exceptions.
The structure of a try-catch statement block for exception handling is as below:
try
{
// part of the program where an exception might occur
}
catch (exceptiontype1 argument1)
{
// Handle exception of the exceptiontype1
}
catch (exceptiontype2 argument2)
{
// Handle exception of the exceptiontype2
}
finally
{
//Code to be executed when the try block exits
}
The try block is examined during execution to detect any exceptions that may be thrown by any statements or any
calls to methods within the block. If an exception is thrown, an exception object is created and thrown. The program
execution stops at that point and control enters the catch block whose argument matches the type of the exception
object thrown. If a match is found the statements in that catch block are executed for handling the exception.
If no exception is thrown during execution of the statements in the try block, the catch clauses that follow the try block
are not executed. Execution continues at the statement after the last catch clause.
The optional finally block is always executed when the try block exits. This means the finally block is executed whether
an exception occurs or not. Programmers use this block to put in clean up code, for example, freeing up resources
allocated in the try block.
248 Touchpad Information Technology-XII

