Exception in Java





What is exception ?

Exception is an abnormal condition that occurs during the execution of a program, & due to which the normal flow of the program's instructions may disrupt.

Example :

class Test
{
 public static void main(String[] ar)
  {
   System.out.println("Hello");
   System.out.println(5/0);
   System.out.println("Hello Again");
  }
}
OUTPUT :
Hello
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Test.main(Test.java:8)    

In the above example, you can see that the last statement is not executed.


What is exception handling ?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL etc.


Why do we handle the exception ?

The main advantage of exception handling is to maintain the normal flow of the application, and to prevent abnormal termination of program.


Types of Exception :

  • All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy.

  • Error

  • Exception
        Checked Exception

        UnChecked Exception


Exception classes Hierarchy :

prowessapps.in

CHEKCED/COMPILE TIME EXCEPTION :

  • Exception and its sub classes are checked or compile time exception.

  • For checked exceptions, compiler prompts either to provide exception handler block or exception to be thrown.


UNCHECKED/RUNTIME EXCEPTION :

  • RuntimeException and its sub classes are unchecked or run time exception.

  • For unchecked exceptions, compiler does not prompt to provide handler.


SOME COMMON EXCEPTION :

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) where ArithmeticException occurs

      If you divide any number by zero.

    e.g. int a = 50/0;

2) where NullPointerException occurs

      If you have null value in any reference-variable, performing any operation by the variable occurs an NullPointerException.

 String s = null;
 //NullPointerException
 System.out.println(s.length());

3) where NumberFormatException occurs

      The wrong formatting of any value.

 String s="12x";
 //NumberFormatException
 int i=Integer.parseInt(s);

4) ArrayIndexOutOfBoundsException

      If you are accessing any wrong index

 int ar[]=new int[5];
 //ArrayIndexOutOfBoundsException
 a[6]=50;

5) Many more like : ClassCastException etc..

Exception Handling :

Java exception handling is managed via five keywords:

  1. try
  2. catch
  3. finally
  4. throw, and
  5. throws

try :

A try block contains multiple statements that may cause different types of exceptions but only one exception can accurr at a time, then execution control jumps to associated and apporopriate catch block.

The try block must be followed by either one or more catch, or finally block.


catch :

The catch block we use to catch the exception throw by try block by mentioning the type of Exception.


Syntax :


1. try with catch

try{
//code that might throw exceptions
}
catch(Exaception-Type ref){
}           


2. try with catch and finally

try{
//code that might throw exceptions
}
catch(Exaception-Type ref){
}
finally{
}           


3. try with finally

try{
//code that might throw exceptions
}
finally{
}           


4. try with multiple-catch

try{
//code that might throw exceptions
}
catch(Exaception-Type ref){
}
catch(Exaception-Type ref){
}           

Note :Rules for Multiple-catch :
All catch blocks must be ordered from most specific to most general type, in other words, child come first in order.
Ex: catch for ArithmeticException must come before catch for Exception.


Problem without exception handling :

class Test
{
 public static void main(String[] ar)
  {
   System.out.println("Hello");
   System.out.println(5/0);
   System.out.println("Hello Again");
  }
}
OUTPUT :
Hello
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Test.main(Test.java:8)    

In the above example, you can see that the last statement is not executed.

Solution with exception handling :

class Test
{
 public static void main(String[] ar)
  {
   System.out.println("Hello");
   try{
     System.out.println(5/0);
    }
   catch(ArithmeticException e)
    {
     System.err.println(e);
    }
   System.out.println("Hello Again");
  }
}
OUTPUT :
Hello
java.lang.ArithmeticException: / by zero
Hello Again

Now, you can see the rest of code get executed.


try with multiple catch:

class Test
{
 public static void main(String[] ar)
 {
  int a [] = new int[5];
  int i;
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter Element");
  for(i = 0;i< a.length;i++)
     a[i] = sc.nextInt();
  try{
System.out.print("Enter index to divide:");
   int index = sc.nextInt();
   System.out.println(a[index]/0);
  }
  catch(ArithmeticException e)
   {
    System.err.print("Exception ");
    System.err.println(e.getMessage());
   }
  catch(ArrayIndexOutOfBoundsException e)
   {
     System.err.print("Exception ");
     System.err.println(e.getMessage());
   }
  catch(Exception e){
    System.err.print("Array Index Excp.");
    System.err.println(e.getMessage());
   }
  System.out.println("End Program");
 }
}
OUTPUT 1:
Enter Element
1
2
3
4
5
Enter index to divide: 5
Array Index Excp. 5 
End Program
OUTPUT 2:
Enter Element
1
2
3
4
5
Enter index to divide :3
Exception / by zero 
End Program

finally

Finally is always executed whether exception is handled or not.

Java finally block follows try or catch block.

For each try block, there can be zero or more catch blocks, but there will be only one finally block.

There is only one situation when finally not executed, if program exits (either by calling System.exit( ) or by causing a fatal error ).

Example :

import java.util.Scanner;
public class Test
{
 public static void main(String[] ar)
  {
   try{
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter two no.");
    int a = sc.nextInt();
    int b = sc.nextInt();
 System.out.print("Division  = "+a/b);
   }
   catch(Exception e)
    {
   System.err.println(e.getMessage());
    }
   finally
    {
  System.out.println("finally block");
    }
   System.out.println("Program End");
  }
}       
OUTPUT 1
Enter two no.2
0
/ by zero
finally block
Program End
OUTPUT 2
Enter two no.
4
2
Division  = 2
finally block
Program End

Nested try block

The try block within a try block is known as nested try block.

Syntax :

try  
{  
    statement 1;  
    statement 2;  
    try  
    {  
        statement 1;  
        statement 2;  
    }  
    catch(Exception e)  
    {  
    }  
}  
catch(Exception e)  
{  
}      

throws keyword :

Handling Checked Exception :

A checked exception is some subclass of Exception ( or Exception itself ), excluding class RuntimeException and its subclass.

Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown, e.g. IOException thrown by java.io.FileInputStream's read() method.

Checked exceptions are those exceptions, which you have to be must handled or declared to be thrown, otherwise your source code won't be compile.

Its always a good programming practice to use try, catch for handling the exception, other alternative is to use throws the exception.

Syntax :

method_name() throws exceptionClassName
{
//method code  
}                  
            

Example :

import java.io.FileInputStream;
import java.io.FileNotFoundException;
class ThrowsDemo
{
 public static void main(String []ar) throws FileNotFoundException
  {
    FileInputStream fis=null;

/* if you create an object of FileInputStream, it throws a checked exception java.io.FileNotFoundException, either you can use try-catch or throws .*/

   fis = new FileInputStream("a.txt");
   //rest code
  }
}           

throw keyword :

The Java throw keyword is used to explicitly throw an exception.

Syntax :

throw ThrowableInstance;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

The flow of execution stops immediately after the throw statement.

You can throw either checked or unchecked exception in java by throw keyword.

The throw keyword is mainly used to throw custom exception.

Example :

class ThrowDemo {
public static void main(String []ar)
{
 int a = 10;
 int b = 20;
 int c = a / b;
 if(c < 1){
 ArithmeticException ae = new ArithmeticException("Denominator is Greater");
 throw ae; 
 }
 System.out.println(“Division : ”+c);
}//End Of Main
}//End Of ThrowDemo class
OUTPUT :
Exception in thread "main" java.lang.ArithmeticException: Denominator is Greater
	at ThrowDemo.main(Test.java:10)

Custom Exception :

Custom exception means you can create your own exception.

Example :

class MyException extends Exception
{
  MyException (String e)
  {
    super(e);
  }
}          

class Test
{
  static void validate(int age)throws MyException
  {  
    if(age<18)  
     throw new MyException("Minor");
    else  
     System.out.print("Welcome to vote");
   }  
 public static void main(String []ar)
  {
    try{
      validate(13);
    }
    catch(Exception e)
    {
     System.err.print("Exception Occurred: "+e);
    }
  }
}           
OUTPUT :
Exception occured: MyException: Minor

Next topic is multithreading




 













Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in



CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved