Exception Handling in Java(With Examples)

Exception Handling

Exception is an abnormal condition in a java program which disrupts the normal flow the program.Few examples are bad coding, wrong input data, network connectivity issue etc.

Technically exception is and object that contains the exceptional details like error message and line at which issue has happened etc.When such a situation arise in any java program,

Exception Object will be created and thrown from the method which contants the faulty code.Then that method has to handle that exception by catching it or rethrowing it to the caller method if it does not handle it.

But ultimately someone has to catch it and handle it.There are few terms related to exception handling:

1) try is the block of code which can throw the exception,so such a piece of code should be enclosed inside try block.

2) catch block is the place where such exception will be handled.

3) throw is used when program intentionally want to generate the exception.for example when someone has entered negative age as input which can’t be possible so in that case program will throw the error since we can’t proceed with negative age.

4)throws keyword will be used by method which are raising the exception but are unable to handle it so they inform the caller method that this method might throw an exception by using throws keyword.

5)finally block will be written for executing the statements which must be executed whether exception occurs or not.for example if we have opened any file stream that has to be closed, no matter exception is thrown or not so file object closure is a good candidate for finally block.

Here is the structure:

   try {

          // block of code which can generate/raise exception

     }

     catch (IOException e) {

          // exception handler for IO(input/output) type of exception

     }

     catch (SqlException e) {

                   // exception handler for SQL(database) type of exception

     }

     finally {

          // block of code that must be executed in both cases like db connection close etc

     }

Super class for all exceptions are Throwable.Exception and Error both are the subclasses of Throwable.

As we mentioned above all runtime issues which program has to handled comes under Exception.Error class objects are the situation which a program is not supposed to handle in normal circumstances.

For example Out of memory error thrown by java can’t be handled by program once it is generated.

On the other side if program does not handle the exception then program will be terminated after that statement and remaining statements will not be executed after exception is generated.

Java’s built-in Exceptions:

Leave a comment