Exception Handling
Exception Handling
Java programming language has the following class hierarchy to support the
exception handling mechanism.
Reasons for Exception Occurrence
Several reasons lead to the occurrence of an exception. A few of them are as
follows.
When we try to open a file that does not exist may lead to an exception.
When the user enters invalid input data, it may lead to an exception.
When a network connection has lost during the program execution may lead to an
exception.
When we try to access the memory beyond the allocated range may lead to an
exception.
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked
exceptions as the compiler checks them during compilation to see whether the
programmer has handled them or not. If these exceptions are not
handled/declared in the program, you will get compilation error. For example,
SQLException, IOException, ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These
exceptions are not checked at compile-time so compiler does not check whether
the programmer has handled them or not but it’s the responsibility of the
programmer to handle these exceptions and provide a safe exit. For example,
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Try Catch in Java – Exception handling
Try block
The try block contains set of statements where an exception can occur. A try block
is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must be followed by catch blocks or finally block
or both.
While writing a program, if you think that certain statements in a program can
throw a exception, enclosed them in try block and handle that exception.
Catch block
A catch block is where you handle the exceptions, this block must follow the try
block. A single try block can have several catch blocks associated with it. You can
catch different exceptions in different catch blocks. When an exception occurs in
try block, the corresponding catch block that handles that particular exception
executes. For example if an arithmetic exception occurs in try block then the
statements enclosed in catch block for arithmetic exception executes.
Example: try catch block
If an exception occurs in try block then the control of execution is passed to the
corresponding catch block. A single try block can have multiple catch blocks
associated with it, you should place the catch blocks in such a way that the generic
exception handler catch block is at the last(see in the example below).
The generic exception handler can handle all the exceptions but you should place
is at the end, if you place it at the before all the catch blocks then it will display
the generic message. You always want to give the user a meaningful message for
each type of exception rather then a generic message.
Multiple catch blocks in Java
The example we seen above is having multiple catch blocks, lets see few rules about
multiple catch blocks with the help of examples.
1. As I mentioned above, a single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions. Whether it is
ArrayIndexOutOfBoundsException or ArithmeticException or NullPointerException
or any other type of exception, this handles all of them.
3. If you are wondering why we need other catch handlers when we have a generic that
can handle all. This is because in generic exception handler you can display a message
but you are not sure for which type of exception it may trigger so it will display the
same message for all the exceptions and user may not be able to understand which
exception occurred. Thats the reason you should place is at the end of all the specific
exception catch blocks
4. If no exception occurs in try block then the catch blocks are completely ignored.
5. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException
catch(NullPointerException e) is a catch block that can handle NullPointerException
6. You can also throw exception.
This example consists of
there are multiple catch
blocks and these catch
blocks executes sequentially
when an exception occurs in
try block. Which means if
you put the last catch block
( catch(Exception e)) at the
first place, just after try
block then in case of any
exception this block will
execute as it can handle
all exceptions. This catch
block should be placed at the
last to avoid such situations.
How to Catch multiple exceptions
To handle multiple exceptions and how to write them in a correct order so that
user gets a meaningful message for each type of exception.
Catching multiple exceptions
Lets take an example to understand how to handle multiple exceptions.
Parent try Catch block: No exception occurred here so the “Next statement..”
displayed.
The important point to note here is that whenever the child catch blocks are not
handling any exception, the jumps to the parent catch blocks, if the exception is
not handled there as well then the program will terminate abruptly showing
system generated message.
Java Finally block – Exception handling
A finally block contains all the crucial statements that must be executed
whether exception occurs or not. The statements present in this block will
always execute regardless of whether exception occurs in try block or not such
as closing a connection, stream etc.
1. A finally block must be associated with a try block, you cannot use finally
without a try block. You should place those statements in this block that must
be executed always.
2. Finally block is optional, as we have seen in previous tutorials that a try-catch
block is sufficient for exception handling, however if you place a finally block
then it will always run after the execution of try block.
3. In normal case when there is no exception in try block then the finally block is
executed after try block. However if an exception occurs then the catch block is
executed before finally block.
4. An exception in the finally block, behaves exactly like any other exception.
5. The statements present in the finally block execute even if the try block
contains control transfer statements like return, break or continue.
Lets see an example to see how finally works when return statement is present
in try block:
Another example of finally block and return statement
You can see that even though we have return statement in the method, the
finally block still runs.
Cases when the finally block doesn’t execute
The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.
Finally and Close()
close() statement is used to close all the open streams in a program. Its a good
practice to use close() inside finally block. Since finally block executes even if
exception occurs so you can be sure that all input and output streams are
closed properly regardless of whether the exception occurs or not.
Finally block without catch
A try-finally block is possible without catch block. Which means a try block
can be used with finally without having a catch block.
try-catch-finally block
Either a try statement should be associated with a catch block or with finally.
Since catch performs exception handling and finally performs the cleanup,
the best approach is to use both of them.
Examples of Try catch finally blocks
Example 1: The following example demonstrate the working of finally block
when no exception occurs in try block
Example 2: This example shows the working of finally block when an exception
occurs in try block but is not handled in the catch block:
On the other hand unchecked exception (Runtime) doesn’t get checked during
compilation. Throws keyword is used for handling checked exceptions . By
using throws we can declare multiple exceptions in one go.
What is the need of having throws keyword when you can handle
exception using try-catch?
The throws does the same thing that try-catch does but there are some cases
where you would prefer throws over try-catch. For example:
Lets say we have a method myMethod() that has statements that can throw
either ArithmeticException or NullPointerException, in this case you can use
try-catch as shown below:
But suppose you have several such methods that can cause exceptions, in that
case it would be tedious to write these try-catch for each method. The code
will become unnecessary long and will be less-readable.
One way to overcome this problem is by using throws like this: declare the
exceptions in the method signature using throws and handle the exceptions
where you are calling this method by using try-catch.
Another advantage of using this approach is that you will be forced to handle
the exception when you call this method, all the exceptions that are declared
using throws, must be handled where you are calling this method else you will
get compilation error.
Example of throws Keyword
In this example the method myMethod() is throwing two checked
exceptions so we have declared these exceptions in the method
signature using throws Keyword. If we do not declare these exceptions then
the program will throw a compilation error.
Throw vs Throws in java
Throws clause is used to declare an exception, which means it works similar
to the try-catch block. On the other hand throw keyword is used to throw an
exception explicitly.
If we see syntax wise than throw is followed by an instance of Exception class
and throws is followed by exception class names.
For example:
throw new ArithmeticException("Arithmetic Exception");
and
throws ArithmeticException;
Throw keyword is used in the method body to throw an exception, while
throws is used in method signature to declare the exceptions that can occur in
the statements present in the method.
You can throw one exception at a time but you can handle multiple exceptions
by declaring them using throws keyword.
For example:
Throw Example
Throws Example
User defined exception in java
In java we can create our own exception class and throw that exception using
throw keyword. These exceptions are known as user-
defined or custom exceptions.
Example of User defined exception in Java
Another Example of Custom Exception
In this example we are throwing an exception from a method. In this case we
should use throws clause in the method signature otherwise you will get
compilation error saying that “unhandled exception in method”.
Checked and unchecked exceptions in java with examples
There are two types of exceptions: checked exception and unchecked exception. The
main difference between checked and unchecked exception is that the checked
exceptions are checked at compile-time while unchecked exceptions are checked at
runtime.