Exception Handling in Java

In Exception Handling, we will cover following:-
1) What is Exception Handling?
2) Keywords used in Exception Handling
3) Using the keywords try and catch
4) Exception Hierarchy
5) Handling multiple exceptions in a single try block
6) Obtaining description of an Exception
7) Using the keyword throw
8) Java's classification of Exception
    1) Checked Exception  
    2) Unchecked Exception
9) Using the keyword finally
10) Creating user defined exception classes 
11) Multi catch feature of Java

What is Exception Handling?  
The word Exception in the world of Java means Run-Time errors and the word exception handling means the way our program behaves whenever these Run-time errors occur.
But before we can understand the importance of exception handling, we must first understand how java behaves by default whenever an exception occurs.
Whenever an exception occurs in Java, the JVM takes two actions by default:-
1. It immediately terminates our program as soon as an exception occurs.
2. It displays a technical error message related to the exception on our output screen.

Both the above behaviors are very much non user friendly because,
1. Terminating a program will not allow further code to execute even if that code has no relation with the exception that has occurs.
2. If the error message will be technical the user will not be able to understand the problem and might repeat wrong input. 

To change both the above behaviors Java strongly recommends to its programmers to apply exception handling mechanism in their program. So we can say that by using exception handling our program will not be terminated abnormally and we can also make our messages user friendly. 
Thus, Exception Handling mechanism is an integral part of every java application and should always be used. 

Keywords used in Exception Handling:-  
Java provides us five keywords related to exception handling.
Each of them has a unique use and must be used wisely in our program.

Using the keyword try and catch:- In a method, there can be more than one statements that might throw exception, so put all these statements within its own try block and provide separate exception handler within own catch block for each of them.
There cannot be any other line between a try and a catch block, they should be continuous.
A try block can have multiple catch blocks.
All exceptions are predefined classes in java. If no catch block matches the exception object then java shows its default behavior.

Syntax of try and catch block:- 

Example:-
Output:-

Exception Hierarchy:-

The Throwable class is the super class of all Errors and Exceptions classes in Java. It is also available in the package java.lang.

Important child classes of the class Exception:-

Handling multiple exceptions in a single try block:- 
for example,

Java rule's on multiple catch:- 
Java has a very strict rule while using multiple catch for a try block. The rule is that, a a parent class of exception hierarchy cannot come before its child class. In other word, catch of parent class should never be appear before catch of child class.
This is because a reference of parent class can easily point to the child class object and hence, the child class catch block will never run.

Example:-

Obtaining description of an exception:-
Whenever an exception occurs in try block, we know that java creates an object of a particular Exception class and moves out of the try block. Within this object Java stores some very important details about the Exception. 
As a programmer when we  debug our program, these information's are very helpful for us. So, Java has provided us some very important methods using we can obtain details about the Exception.  
These methods are:-
1) public String getMessage( )
2) public String toString( )
3) public void printStackTrace( )

1. public String getMessage( ):- This method belongs to the class Throwable and returns Java's error message related to the Exception.
Example:-
Output:-

2. public String toString( ):- This method belongs to the class Object and thus, it is inherited by every Java class. (Both predefined and user defined classes
Following are some very important features of this method:-
1. This method is automatically called by Java as soon as we pass the name of an object reference to System.out.println() or System.out.print().
2. If a class does not override this method then java executes the Object class version of this method which returns Hashcode.
Hashcode:- Hashcode in java is an encrypted alphanumeric value produce by Java by applying some special algorithms on objects address.
Since it  is generated using objects address, it is always unique for every unique object.
But it is of no use to programmer or user. 
Example:-
Output:-

3. However it is strongly recommended that we must properly override this method in our class and return String representation of object data members from this method as shown below:-
Example:-
Output:-

4. All java classes including Exception classes have properly overridden this method and return String representation of their object values. 
Example:-
Output:-
This output is generated by the method toString() of java.util.Date class.

Similarly consider the following code:-
Output:-
This output is also generated by the method toString() of Exception class.

3. public void printStackTrace( ):- This method belongs to the class Throwable and prints the complete details related to the Exception  which include five information's:- 
1. Name of the Exception
2. Error message related to the Exception
3. Name of the class as well as the name of the method where the exception occurred
4. Name of the source code file
5. Line no. where exception occurred

Example:-

Output:-

Using the keyword throw:-
The keyword throw in java is used by programmer for explicitly generating an exception from the try block. This normally happens when we want to force Java to generate exception on our condition.
The general syntax of using throw is:-

Let us consider through a question-
Write a program to accept two integers from the user and divide them.
Make sure that if the numerator entered is 0 or negative then generate your own exception displayed “Numerator must be positive" and also if the denominator entered is 0 then show Java's exception message.
Solution:-

Output:-

Java's classification of Exception:-
In Java exceptions are broadly categorized to be of two types- 
1. Checked Exceptions
2. Unchecked Exceptions

Unchecked Exceptions:- Unchecked Exceptions in Java are those exception which may or may not be handle by a programmer that is Java never forces  a programmer to handle these exceptions. The program would be compiled and executed by Java.
The class RuntimeException and all its child classes come in this category.

Checked Exceptions:- This in java is called handle of declare rule. These are those exceptions for which java forces programmer to do either of the following do:-
1. The programmer should use try and catch to handle it.
Or
2. The programmer should use the keyword throws followed by the name of the checked Exception in the header of his method.
If every method uses throws, the ultimately the responsibility goes to to the JVM which will follow the standard mechanism of handling the exception.
All Exception classes which are not the child class of RuntimeException fall in this category. 
Like- SQLExceptionIOException etc… 

Example:-

Output:-

Using the keyword finally:-
While developing applications in Java, we may have some important statements in our program whose execution is very much important for successful behavior of our program.
Normally these statements are resource de-allocation statements like- closing a file or disconnecting with a database.
In such situations, Java provides us a very special block which can be used with try called as the “finally” block.
The specialty of  this block is that Java guarantees its execution in every possibility that is if no exception arises in try block then also finally runs, if exception occurs and our catch block handles it then also finally runs and most importantly if exception occurs and we don't catch it then also finally run.

Important points regarding finally keyword:-
1. Finally can not come without try block.
2. Every try block either requires a catch block or finally block.
3. A try block can have only one finally block but, a try block can have zero or  numerous catch blocks. 
4. If an exception occurs outside try block in that case finally block is not executed and also when the method System.exit() is used. 

Syntax of finally block:-
Example:-

Output:-

Creating user defined exception classes:-
In Java unfortunately for every Run time error, we can not find any matching exception class. In such cases Java recommends programmer to define his own exception classes. Such classes are called customized exception classes or user defined exception classes.
For example- Suppose we want to generate an Exception, If the numerator given by the user is 0. In such cases Java strongly recommends that we should define our own exception classes.
To create an exception class we need to follow some steps, which are as follows:-
1. Inherit or extend any of the predefined exception class in our own exception class.
2. Provide a parameterized constructor so that exception message can be set and passed on to parent class constructor.
For example- By the name InvalidNumeratorException and make it derived class of any Exception class of Java, preferably java.lang.Exception.

Output:-

Important points:-
1. The customized exceptions become checked exception if we inherit the base class Exception.
2. Since, only RuntimeException and it's child classes are unchecked in nature, so programmer has to specifically inherit anyone of those to create and unchecked exception class.

Multi catch feature of Java:-
we can use a single catch to handle multiple exceptions.
This feature was introduced in java from 7th version.
Syntax:-


Post a Comment

0 Comments