X

Play AlgoQuiz

Rate Us :



Share with Friends :

Menu

Exception Handling :

Whenever we develop any project in real time it should work in all circumstances (mean in any operation either in error or error free). For every technology or every programming language, if we use it for implementing real time applications and if the end user commits a mistake then by default that language or technology displays system error messages which are nothing but run time errors.

Run time errors in Java are known as exceptions.

System error messages are those which are unable to understand by end user or client.

User friendly messages are those which are understandable by end user or client.

Exceptional handling is a mechanism of converting system error messages into user friendly messages. Errors are of two types. They are compile time errors and run time errors.

Compile time errors are those which are occurring because of poor understanding of the language.

Run time errors are those which are occurring in a program when the user inputs invalid data.

The run time errors must be always converted by the Java programmer into user friendly messages by using the concept of exceptional handling. In Java run time environment, to perform any kind of operation or task or an action will be performed with respect to either class or an interface. Whenever we pass invalid data as an input to the Java program then Java run time environment displays an error message, that error message is treated as a class.


Runtime Stack Mechanism :

For every thread JVM will create a runtime stack. All the method call performed by the thread will be stored in the stack. Each entry in the stack is called activation record or stack frame. After completing every method call JVM deletes the corresponding entry from the stack i.e. just before terminating the thread JVM destroys the stack.


Default Exception Handling in Java :

If any exception raised, the method in which it is raised is responsible to create exception object by including the following information :-

  • Name of Exception




  • Description of Exception




  • Location of Exception (stack trace)




After creating exception object, method handover that exception object to the JVM.

JVM checks whether the method contains any exception handling code or not.

If the method contains any exception handling code then it will be executed and continue rest of the program normally.

If it doesn't contain handling code then JVM terminates that method abnormally and removes corresponding entry from the stack.

JVM identifies the caller method and checks whether caller method contains any handling code or not. If the caller method doesn't contain any handling code then JVM terminates that caller method also abnormally and removes corresponding entry from the stack. This process will continue until main() method execution and if the main() method also doesn't contain handling code then JVM terminates the main() also abnormally and removes corresponding entry from stack.

Just before terminating the program abnormally, JVM handover the responsibility of exception handling to the default exception handler. Default exception handler just print information to the console in the following format :

Name of Exception : Description
Location (Stack Trace)

Types of exceptions:


  • In Java we have two types of exceptions, they are predefined exceptions and user or custom defined exceptions.

  • Predefined exceptions are those which are developed by Sun Microsystem and supplied as a part of JDK to deal with universal problems. Some of the universal problems are divided by zero, invalid format of the number, invalid bounce of the array, etc.

  • Predefined exceptions are divided into two types. They are asynchronous exception and synchronous exceptions.

  • Asynchronous exceptions are those which are always deals with hardware problems. In order to deal with asynchronous exceptions there is predefined class called java.lang.Error. java.lang.Error class is the super class for all asynchronous exceptions.

  • Synchronous exceptions are one which always deals with programmatic errors. In order to deal with synchronous exceptions we must use a predefined class java.lang.Exception class. java.lang.Exception is the super class for all synchronous exceptions. Synchronous exceptions are divided into two types. They are checked exceptions and unchecked exceptions.

  • A checked exception are those which are checked by compiler for smooth execution of the program at runtime. Example : FileNotFoundException etc.

  • Unchecked exceptions are those which are not checked by compiler for smooth execution of the program at runtime. Example : ArithmeticException, NumberFormatException, ArrayIndexOutOfBoundsException etc.


Exception Hierarchy :

Throwable class acts as a root for entire Java Exception hierarchy. It has the following child classes :

  • Exception




  • Error




Partially checked and Fully checked exception :

A checked exception is said to be partially checked if and only if some of it's child classes are unchecked. Example : Exception

In Java, the only partially checked exceptions are Exception and Throwable.

A checked exception is said to be fully checked if and only if all of it's child classes are checked. Example : IOException





An exception is an object which occurs at run time which describes the nature of the message. The nature of the message can be either system error message or user friendly message.





Whenever we pass irrelevant input to a Java program, JVM cannot process the irrelevant input.





Since, JVM is unable to process the user input, it can contact to JRE for getting an appropriate exception class.





JRE contacts to java.lang.Throwable for finding what type of exception it is.





java.lang.Throwable decides what type of exception it is and pass the message to JRE.





JRE pass the type of exception to Java API.





Either java.lang.Error class or java.lang.Exception class gives an appropriate exception class to JRE.





JRE will give an appropriate exception class to JVM.





JVM will create an object of appropriate exception class which is obtained from JRE and it generates system error message.





In order to make the program very strong (robust), Java programmer must convert the system error messages into user friendly messages by using the concept of exceptional handling. User friendly messages are understand by normal user effectively hence our program is robust.





Syntax for exceptional handling: In order to handle the exceptions in Java we must use the following keywords. They are try, catch, finally, throws and throw. try { Block of statements which are to be monitored by JVM at runtime (or problematic errors); } catch (Type_of_exception1 object1) { Block of statements which provides user friendly messages; } catch (Type_of_exception2 object2) { Block of statements which provides user friendly messages; } catch (Type_of_exception3 object3) { Block of statements which provides user friendly messages; } . . . finally { Block of statements which releases the resources; }


Try block:

  • This is the block in which we write the statements which are to be monitored by JVM at runtime i.e. try block must contain those statements which causes problem at runtime.

  • If any exception is taking place, the control will jump automatically to appropriate catch block.

  • If any exception is taking place in try block, execution will be terminated and the rest of the statements in try block will not be executed at all and the control will go to catch block.

  • For every try block we must have atleast one catch block. It is highly recommended to write 'n' number of catch for 'n' number of problematic statements.

  • If try with multiple catch blocks takes place then the order of catch blocks is very important and it should be from child class to parent class.

  • If we are taking it from parent class to child class then we will get compile time error saying exception xxxx has already been caught.

Catch block:

  • This is used for providing user friendly messages by catching system error messages.

  • In the catch block we must declare an object of the appropriate execution class and it will be internally referenced JVM whenever the appropriate exception taking place.

  • If we write 'n' number of catch as a part of Java program then only one catch will be executing at any point.

  • After executing appropriate catch block even if we use return statement in the catch block the control never goes to try block.

Example 1:

class Example { public static void main (String[ ] args) { try { System.out.println(10/0); } catch(Exception e) { System.out.println("Exception"); } catch(ArithmeticException e) { System.out.println("ArithmeticException"); } } }

Output:

Compile time error : exception ArithmeticException has already been caught

Example 2:

class Example { public static void main (String[ ] args) { try { System.out.println(10/0); } catch(ArithmeticException e) { System.out.println("ArithmeticException"); } catch(Exception e) { System.out.println("Exception"); } } }

Output:

ArithmeticException

Finally block:

  • It is never recommended to define clean up code within try block because there is no guarantee for the execution of every statement. It is never recommended to define clean up code with catch block also because it won't be executed if there is no exception. So we require a place to maintain clean up code which should be executed always irrespective of whether exception raised or not and whether handle or not. Such type of place is nothing but finally block. Hence, the main purpose of finally block is to maintain clean up code which should be executed always.

  • This block contains same statements which releases the resources which are obtained in try block (resources are opening files, opening databases, etc.).

  • Writing the finally block is optional.

Example 1:

class Example { public static void main (String[ ] args) { try { System.out.println("try"); } catch(Exception e) { System.out.println("catch"); } finally { System.out.println("finally"); } } }

Output:

try finally

Example 2:

class Example { public static void main (String[ ] args) { try { System.out.println("try"); System.out.println(10/0); } catch(Exception e) { System.out.println("catch"); } finally { System.out.println("finally"); } } }

Output:

try catch finally

Example 3:

class Example { public static void main (String[ ] args) { try { System.out.println("try"); System.out.println(10/0); } catch(NullPointerException e) { System.out.println("catch"); } finally { System.out.println("finally"); } } }

Output:

try finally Runtime Exception : java.lang.ArithmeticException: / by zero

Example 4:

class Example { public static void main (String[ ] args) { try { String s1=args[0]; String s2=args[1]; int n1=Integer.parseInt(s1); int n2=Integer.parseInt(s2); int n3=n1/n2; System.out.println ("DIVISION VALUE = " + n3); } catch (ArithmeticException Ae) { System.out.println ("DONT ENTER ZERO FOR DENOMINATOR..."); } catch (NumberFormatException Nfe) { System.out.println ("PASS ONLY INTEGER VALUES..."); } catch (ArrayIndexOutOfBoundsException Aioobe) { System.out.println ("PASS DATA FROM COMMAND PROMPT..."); } finally { System.out.println ("I AM FROM FINALLY..."); } } }

Output:

PASS DATA FROM COMMAND PROMPT... I AM FROM FINALLY...

  • finally block dominates return statement. If there is any return statement present inside the try and catch block then first finally will be executed and then return will be executed.

Example :

class Example { public static void main (String[ ] args) { try { System.out.println("try"); return; } catch(Exception e) { System.out.println("catch"); } finally { System.out.println("finally"); } } }

Output:

try finally
Note :

There is only one situation where the finally block won't be executed is whenever JVM shut down i.e. whenever we are using System.exist(0);

Example :

class Example { public static void main (String[ ] args) { try { System.out.println("try"); System.exit(0); } catch(Exception e) { System.out.println("catch"); } finally { System.out.println("finally"); } } }

Output:

try

Various possible combination of try-catch-finally block :


try
{

}
catch(Exception e)
{

}//valid
try
{

}
catch(ArithmeticException e) //child class
{

}
catch(Exception e) //parent class
{

}//valid
try
{

}
catch(Exception e) //parent class
{

}
catch(ArithmeticException e) //child class
{

}// Compile time error :  exception ArithmeticException has already been caught
try
{

}
catch(ArithmeticException e)
{

}
catch(ArithmeticException e)
{

}// Compile time error :  exception ArithmeticException has already been caught
try
{

}
catch(Exception e1)
{
 try
 {

 }
 catch(ArithmeticException e2)
 {

 }
}//valid
try
{

}
finally
{

}//valid
try
{

}//Compile time error : 'try' without 'catch', 'finally' or resource declarations
catch(Exception e)
{

}//Compile time error : 'catch' without 'try'
finally
{

}//Compile time error : 'finally' without 'try'
try
{

}
System.out.println("Algo");
catch(Exception e)
{

}//Compile time error : 'try' without 'catch', 'finally' or resource declarations
//Compile time error : 'catch' without 'try'
try
{

}
catch(ArithmeticException e)
{

}
System.out.println("Algo");
catch(Exception e)
{

}//Compile time error : 'catch' without 'try'
try
{

}
catch(Exception e)
{

}
System.out.println("Algo");
finally
{

}//Compile time error : 'finally' without 'try'
try
{

}
catch(Exception e)
{

}
finally
{

}
finally
{

}//Compile time error : 'finally' without 'try'
try
{

}
catch(Exception e)
{

}
finally
{
 try
 {

 }
 finally
 {

 }
}//valid
try
{
 try
 {

 }
}
catch(Exception e)
{

}//Compile time error : 'try' without 'catch', 'finally' or resource declarations
try
{
 
}
finally
{

}
catch(Exception e)
{

}//Compile time error : 'catch' without 'try'

throw :


  • Sometimes we can create Exception object manually and handover that object to the JVM explicitly by using throw keyword.

  • Hence, the main objective of throw keyword is to handover the created Exception object manually to the JVM.

Example 1:

class Example { public static void main (String[ ] args) { System.out.println(10/0); } }

Output:

Runtime Exception : java.lang.ArithmeticException: / by zero Note : In this case ArithmeticException object created internally and handover that object automatically by the main() method to JVM.

Example 2:

class Example { public static void main (String[ ] args) { throw new ArithmeticException("/ by zero"); } }

Output:

Runtime Exception : java.lang.ArithmeticException: / by zero Note : In this case we created ArithmeticException object and handover that object to JVM manually by using throw keyword.
  • In general we can use throw keyword for customized exception.

  • If we are trying to throw null reference then we will get NullPointerException.

Example 1:

class Example { static ArithmeticException e; public static void main (String[ ] args) { throw e; } }

Output:

Runtime Exception : java.lang.NullPointerException

Example 2:

class Example { static ArithmeticException e = new ArithmeticException(); public static void main (String[ ] args) { throw e; } }

Output:

Runtime Exception : java.lang.ArithmeticException
  • After throw statement we are not allowed to write any statement directly otherwise we will get compile time error saying unreachable statement.

Example 1:

class Example { public static void main (String[ ] args) { throw new ArithmeticException("/ by zero"); System.out.println("Algo"); } }

Output:

Compile time error : unreachable statement

Example 2:

class Example { public static void main (String[ ] args) { System.out.println(10/0); System.out.println("Algo"); } }

Output:

Runtime Exception : java.lang.ArithmeticException

  • We can use throw keyword only for Throwable type otherwise we will get compile time error saying incompatible types.

Example 1:

class Example { public static void main (String[ ] args) { throw new Example(); } }

Output:

Compile time error : incompatible types required : Throwable found : Example

Example 2:

class Example extends RuntimeException { public static void main (String[ ] args) { throw new Example(); } }

Output:

Runtime Exception : Exception in thread "main" Example


X

MiniDoll :

MiniDoll is an application to learn with fun. You can play it to solve some tricky questions related to Java Programming. Either enjoy playing it alone or discuss with your friends to solve it. It is a simple approach to learn by solving questions. This application has different topics of Java and each topic is divided into three phases. Start solving from initial topic to final topic and by the end of every topic you can boost your concept of that topic.