Exception handling in java

What is exception handling?

Whenever java programme or application runs, java runtime environment make sure it runs smoothly. Runtime environment run java application or programme correctly without any problem. But some abnormal cases the java programmes or application can get into trouble. In such type of abnormal conditions java programme can stop the execution. In these abnormal conditions run time environment also takes care to get information about abnormal condition. Run time environment crates the object having information about the abnormal condition. So our programme should handle the abnormal condition to go ahead for execution. Handling the abnormal conditions in java is called the exception handling.

Implementing exception handling

To implement the exception handling there are three keywords in java.




You have to identify the abnormal conditions in java programme and put that statement in try block and if you want to get the information if abnormal condition occurs, put those statements in catch block, and if you have to execute some statement those has to execute in any conditions either exception occurs or not, put those type of statements in finally block.

The example of try and catch block are below:

try {
// abnormal cases statement goes here
} catch (Exception e) {
// handle exception

If any abnormal condition occurs in try block. The java RTE creates the objects of exception and control goes to catch block, please note the catch blocks take an arguments of type java.lang.Throwable. All type of exceptions in java is the subclasses of java.lang.Throwable class. Using the catch block you can get all information about the exception.

Some fact about try, catch and finally block

1) The try block always comes with either catch or finally block.

2) There should not be any statement in between try and catch and in between catch and finally.

3) If any exception occurs in try block, it stops the execution in try block and creates the object of exception and goes to catch block.

4) You can put the try and catch block anywhere in java programme even in catch block also.

5) The statements which are compulsory to execute either exception occurs or not should be kept in finally block.

6) If you have put any return statement in finally block than there should not be any return statement in try and catch, because it does not make any sense, because the finally block return statement will we execute.

7) Finally block will not execute if and only if you have put System.exit(0) in try or catch block. This statement will throw the execution control from programme.

8) We can keep more than one catch block with one try block, but only one catch block will be executed, all remaining catch block will be skipped.