An ‘exception’ is an event which occurs during the execution of a program that interrupts the normal flow of program. When an error is occurred in a program during execution, an ‘exception object’ is created by the method and it is handed over to the runtime system and it is called ‘throwing an exception’.

Exceptions are mainly of three types: They are

1. Checked exceptions

It is an exception that can’t be foreseen by a programmer.
Eg. FileNotFoundException

2.Runtime exceptions

Runtime exceptions are exceptions that indicate bugs in the program such as logical errors that could have been avoided by the programmer.
Eg. NullPointerException, ArrayIndexOutOfBoundsException

3.Errors

Errors are not exceptions, but problems that are beyond the control of the programmer and the application can’t recover from.
Eg. java.io.IOError

The three exception handler components are:

1.try
2.catch disrupt
3.finally

Putting together the try, catch and finally block will look like the following.

try
{
// protected code
}
catch (ExceptioType1 e1)
{
// catch block
}
finally
{
// code that always executes.
}

We can’t write any code in between try – catch and catch – finally. But we can use multiple catch blocks in between try and finally blocks, each handles the type of exception represented by its argument. The argument type declares the exception type that the catch block can handle. When the runtime system invokes the exception handler, the codes inside the catch block are executed. A catch block should be written after a try block but a finally block is not compulsory.

If an exception is occurred or not, the codes in the finally block are always executed. ‘finally’ is more useful than just exception handling, it allows the programmer to execute the cleanup codes that he wants to execute, no matter what happened in the try block.

The throw and throws keywords

1. throw

We can throw a newly instantiated exception object or an exception object that is caught using the keyword ‘throw’.

2. throws

A method which does not handle a checked exception must be declared with ‘throws’ keyword at the end of the method’s signature. If more than one exception needs to be thrown, it can be separated by commas.

The following method uses throw and throws keywords.
public void example() throws RemoteException
{
// method body
throw new RemoteException();
}

Advantages of exceptions

1.To separate the error handling code from regular code.
2.The ability to report error.
3.To differentiate and group the error types.