How to Java programming- Catching & Handling Exceptions

Exception handling is the process of responding to the occurrence, during computation, of exceptions requiring special processing – often changing the normal flow of program execution. Java includes mainly two types of exception handling.

1.Try-Catch block.
2.Finally block.

1.Try-Catch block.

This section describes how to use the three exception handler components – the try, catch, and finally blocks – to write an exception handler.

Try block.

The try block contains a block of program statements within which an exception might occur. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must follow by a Catch block or Finally block or both.

Try Block

try {
code
}
catch and finally blocks . . .

Catch blocks.

A catch block must be associated with a try block. The corresponding catch block executes if an exception of a particular type occurs within the try block.

Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

A try block can have any number of catch blocks. A catch block that is written for catching the class Exception can catch all other exceptions.

2.Finally block.

Java’s finally block is useful in exception handling and always used in conjunction with a try block. There should at least be one try block that finally block can be associated with. The try encloses a block of code in which exception may occur. When a piece of code throws an exception, it stops processing the remaining code in a try block and transfers the control to an appropriate catch block if a catch block exists (catch block is optional), else control gets transferred to finally block. Both catch and finally are optional, you can omit one of them at a time but not both. Also, there can be more than one catch block associated with a single try block but only one catch block is processed at a time. Also, note that the catch blocks immediately follow the try block.

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.