/* related posts with thumb nails */

Exception Handling & syntax for handling exceptions in Java:

Exception Handling: Handling runtime errors is exception handling. In java, when an abnormal condition occurs within a method then the exceptions are thrown in form of Exception Object i.e. the normal program control flow is stopped and an exception object is created to handle that exceptional condition. If the exception object is not caught and handled properly, the interpreter will display an error message and it will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception.

The purpose of exception handling mechanism is to provide a means to detect and report an "exceptional circumstance" so that appropriate action can be taken. The mechanism performs the following tasks:

1. Find the problem.

2. Inform that an error has occurred (Throw the exception)

3. Receive the error information (Catch the exception)

4. Take corrective actions (Handle the exception)

The error handling code basically consists of two segments, one to detect errors and to throw exceptions and the other to catch exceptions and to take appropriate actions. Exception handling mechanism includes the key words: try, catch, throw, throws and finally.




try
{

Statements that may generate the exception

}
catch(Exception-Type1 a)

{

Statements to process the exception ‘a’

}
catch(Exception-Type2 b)

{

Statements to process the exception ‘b’

}

….

….
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.


Related Topics:

0 comments:

Post a Comment