How Exceptions are Handled:
Syntax: Try-Catch-Finally Blocks
try
{
{
Statements that may generate the exception
}
catch(Exception-Type1 a)
catch(Exception-Type1 a)
{
Statements to process the exception ‘a’
}
catch(Exception-Type2 b)
catch(Exception-Type2 b)
{
Statements to process the exception ‘b’
}
….
….
finally
{
finally
{
Statements to be executed before exiting exception handler
}
try-block: “try” block contains the code in which runtime error may occur. It throws Exception object. A try block must be followed by at least one catch block or a finally block. But, it can be followed by multiple catch blocks. A try block allows another try block within.
catch-block: “catch” block contains the handling code for runtime errors i.e. when run time error occurs, instead of terminating the program, control comes to “catch” block. Program control enters into “catch” block only when the corresponding runtime error occurs. After executing the handling code the control continues with the remaining part of the program. Multiple “catch” blocks can be written to handle different errors. In a “catch” block the exception type must be mentioned.
finally-block: The finally block is always executed, regardless of whether or not an exception is thrown. It is recommended for actions like closing file streams and releasing system resources. Writing the finally block for try-block is optional unless there is no catch-block. If no exception occurs during the running of the try-block, all the catch-blocks are skipped, and finally-block will be executed after the try-block.
0 comments:
Post a Comment