Exception Handling
Exception Handling
Note :The main objective of exception handling is to get the normal termination of
the applicaion.
Types of Exceptions: As per the sun micro systems standards The Exceptions are
divided into three types
1. Checked Exception
2. Unchecked Exception
3. Error
Unchecked Exception:
a. The Unchecked Exception are caused due to end user inputproblems.
b. The exceptions are not checked by compiler are called Unchecked Exception
ex : AE, AIOBE , NPE , NFE...etc
c. These are child class of RuntimeException.
class Test {
public static void main(String[] args) {
System.out.println("ratan");
System.out.println(10/0);
ArithmeticException
int[] a = {10,20,30};
System.out.println(a[6]);
java.lang.ArrayIndexOutOfBoundsException
System.out.println("ratan".charAt(12));
StringIndexOutOfBoundsException
Checked Exception:
a. The checked exceptions are caused due to developer issues.
b. The Exceptions which are checked by the compiler are called Checked
Exceptions.
FileNotFoundException,SQLException,InterruptedException ……..etc
c. these are child class of Exception.
import java.io.*;
class Test
{ public static void main(String[] args)
{ try{
FileInputStream fis = new FileInputStream("abc.txt");
}
catch(FileNotFoundException f)
{ System.out.println("file is not present..."+f);
}
System.out.println("rest of the application");
}
}
Note:
1. un-checked exceptions are caused due to end user input problems.
checked exceptions are caused due to developer mistake.
2. The checked exceptions are safe becaue the compiler will give some information
about the exception at compile time itself.
If the application contains checked exception must handle the exception,
otherwise compiler generates error message.
//errors:
1.The exceptions are occurred due to the fallowing reasons
a. Developer mistakes
b. End-user input mistakes.
But errors are caused due to lack of system resources.
StackOverFlowError, OutOfMemoryError …………etc
Note:
The Throwable class is the superclass of all errors and exceptions in the
Java language.
The root class of only exceptions : Exception
The root class of only error : Error
RuntimeExceptions its child classes & Error its child classes are unchecked
exceptions, remaining all exceptions are checked type.
The class Exception and any subclasses that are not also subclasses of
RuntimeException are checked exceptions.
ex-1 : Whenever exception raised in the try block, the corresponding catch block
executed.
Disadvantages:
a. program terminated abnormally.
b. rest of the application not executed.
Advantages:
a. Program terminated normally
b. Rest of the application executed
ex-2 : In below example catch block is not matched hence program is terminated
abnormally.
try
{ System.out.println("sravya");
System.out.println(10/0);
}
catch(NullPointerException e)
{ System.out.println(10/2);
}
ex 3: If there is no exception in try block the corresponding catch blocks are not
checked.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
}
catch(NullPointerException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}
ex-4: In Exception handling independent try blocks declaration are not allowed.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
}
System.out.println("rest of the app");
}
}
error: 'try' without 'catch', 'finally' or resource
declarations
ex-5: In between try-catch blocks it is not possible to declare any statements.
try
{ System.out.println(10/0);
}
System.out.println("anu");
catch(ArithmeticException e)
{ System.out.println(10/2);
}
ex-6: Once the exception raised in try block the corresponding catch block
executed.
If the exception raised in catch then it is abnormal termination.
try
{ System.out.println(10/0);
}
catch(ArithmeticException e)
{ System.out.println("ratan".charAt(12));
}
ex- 7:
If the exception raised in try block the remaining code of try block is not
executed.
Once the control is out of the try block the control never entered into try block
once again.
Don’t take normal code inside try block because no guarantee all statements in try-
block will be executed or not.
class Test
{ public static void main(String[] args)
{ try{
System.out.println("durga");
System.out.println("ratan");
System.out.println(10/0);
}
catch(ArithmeticException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}
E:\sravya>java Test
Durga
ratan
rest of the app
class Test
{ public static void main(String[] args)
{ try{
System.out.println(10/0);
System.out.println("durga");
System.out.println("ratan");
}
catch(ArithmeticException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}
E:\sravya>java Test
5
rest of the app
case 1: If the exception raised in try block : catch is matched : normal termiation
case 2: If the exception raised in try block : catch is not matched : Abnormal
termiation
case 7: Once the exception raised in try block the remaining code of try block not
executed.
try
{ int num = s.nextInt();
System.out.println(10/num);
System.out.println("ratan".charAt(10));
}
catch(InputMismatchException i)
{ System.out.println("Enter valid data....only integers");
}
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
catch(StringIndexOutOfBoundsException e)
{ System.out.println("durgasoft");
}
System.out.println("Rest of the application....");
}
}
case-2: lazy
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("enter the division value");
try
{ int num = s.nextInt();
System.out.println(10/num);
System.out.println("ratan".charAt(10));
}
catch (Exception e)
{ System.out.println("Exception info..."+e);
}
System.out.println("Rest of the application....");
}
}
try
{ int num = s.nextInt();
System.out.println(10/num);
System.out.println("ratan".charAt(10));
}
//child to parent
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
catch(Exception e)
{ System.out.println("Exception Info..."+e);
}
System.out.println("Rest of the application....");
}
}
The single catch block can handle the multiple exceptions using pipe symbol.
case 1: unchecked
catch(ArithmeticException | ClassCastException a)
catch(NumberFormatException|NullPointerException|StringIndexOutOfBoundsException a)
case 2: checked
catch(FileNotFoundException|InterruptedException a)
case 1:
a. Declare the resource using try block, once the try block is completed the
resource is automatically released.
b. how it is release automatically means it internally uses AutoCloseable.
E:\>javap java.lang.AutoCloseable
public interface java.lang.AutoCloseable {
public abstract void close() throws java.lang.Exception;
}
c. The close() method is invoked automatically on objects managed by the try-with-
resources statement.
ex-1:
case-1. In below code must close the scanner object using close() method.
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Enter a number.....");
int num = s.nextInt();
System.out.println("Your number....."+num);
s.close();
}
}
case-2. Declare the resource using try block, once the try block is completed
the resource is automatically released.
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ try(Scanner s = new Scanner(System.in))
{ System.out.println("enter id");
int a = s.nextInt();
System.out.println("input value="+a);
}
}
}
Observation:
1. If the rsource is not throwing any exception then catch block not required.
try(Scanner s = new Scanner(System.in))
{ logics
}
ex-2:
import java.io.*;
class Test
{ public static void main(String[] args)
{ try(FileInputStream fis = new FileInputStream("abc.txt"))
{ System.out.println("reading data from text file");
}
catch(IOException e)
{ System.out.println("Exceptio raised....");
}
}
}
if the resource is throwing an excpetions so catch block required.
FileNotFoundException : reading the data from file
IOException : exception thrown from implicit call to close()
ex-3: By using try block it is possible to declare more than one resource but every
resource is separated with semicolon.
try(Scanner s = new Scanner(System.in);
FileInputStream fis = new FileInputStream("abc.txt"))
{ //some code here
}
in multiple resources if at lease one resource throws exception then catch is
mandatory.
case 1:
try{
}
catch (){
}
case 2:
try{
}
catch (){
}
fsdfsdf
sdfsdfsdf
try{
}
catch (){
}
case 5:
try
{
}
catch ()
{ try
{
}
catch ()
{
}
}
case 6:
try
{ try
{
}
catch ()
{
}
}
catch ()
{ try
{
}
catch ()
{
}
}
case 1:The developer can print the exceptions msg in three ways,
1) printing reference variable
2) getMessage()
3) printStackTrace()
class Test
{ void m3()
{ try
{ System.out.println(10/0);
}
catch(ArithmeticException ae)
{ System.out.println(ae);
System.out.println(ae.getMessage());
ae.printStackTrace();
}
}
void m2()
{ m3();
}
void m1()
{ m2();
}
public static void main(String[] args)
{ new Test().m1();
}
}
E:\>java Test
java.lang.ArithmeticException: / by zero
/ by zero
java.lang.ArithmeticException: / by zero
at Test.m3(Test.java:3)
at Test.m2(Test.java:12)
at Test.m1(Test.java:15)
at Test.main(Test.java:18)
finally
=======
//Application without finally
try
{ connection open
tx1
tx2
}
catch (exception-name)
{
}
connection closed
Note: To close the connection both normal & abnormal cases use finally block
because the finally block code executed both normal & abnormal cases.
Note: To release the resources both normal & abnormal cases use finally block.
file closing.
Scanner object closing.
Connection closing.
Case 1:NT
try
{ System.out.println("try");
}
catch (ArithmeticException ae)
{ System.out.println("catch");
}
finally
{ System.out.println("finally");
}
case 2: NT
try
{ System.out.println(10/0);
}
catch (ArithmeticException ae)
{ System.out.println("catch");
}
finally
{ System.out.println("finally");
}
case 3:ABT
try
{ System.out.println(10/0);
}
catch (NullPointerException ae)
{ System.out.println("catch");
}
finally
{ System.out.println("finally");
}
case 4: ABT
try
{ System.out.println(10/0);
}
catch (ArithmeticException ae)
{ System.out.println(10/0);
}
finally
{ System.out.println("finally");
}
case 5: ABT
try
{ System.out.println("try");
}
catch(ArithmeticException ae)
{ System.out.println("catch");
}
finally
{ System.out.println(10/0);
}
case 6:
try
{ System.out.println("try");
}
finally
{ System.out.println("finally");
}
Note:
try-catch : valid
try-with resources : valid
try-finally : valid
try-catch : Valid
try-finally : Valid
try-catch-finally : Valid
try-catch-catch : Valid
try-catch-catch-finally : Valid
catch-finally : Invalid
try-finally-finally : Invalid
try-finally-catch : Invalid
try-catch-finally-catch : Invalid
catch-try-finally : Invalid
try-catch-finally-finally : Invalid
try-try-catch-finally : Invalid
case 2:
class Test
{ public static void main(String[] args)
{
try
{ System.out.println("ratan");
System.exit(0);
}
finally
{ System.out.println("finally block");
}
System.out.println("rest of the code");
}
}
interview :
case 1:
class Test
{ public static void main(String[] args)
{ try
{ System.out.println(10/0);
}
catch(Exception e)
{ System.out.println("ratan".charAt(20));
}
finally
{ int[] a={10,20,30};
System.out.println(a[9]);
}
}
}
case 2:
class Test
{ int m1()
{ try
{ return 10;
}
catch(Exception e)
{ return 20;
}
finally
{ return 30;
}
}
public static void main(String[] args)
{ int a = new Test().m1();
System.out.println("return value="+a);
}
}
st-1 st-2
try
{ st-3 st-4
try
{ st-5 st-6
}
catch ()
{ st-7 st-8
}
}
catch ()
{ st-9 st-10
try
{ st-11 st-12
}
catch ()
{ st-13
st-14
}
}
finally
{ st-15 st-16
}
st-17 st-18
case 6: exp raised in st-6 inner catch is not matched but outer catch is matched.
1,2,3,4,5,9,10,11,12,15,16,17,18 normal termination
throws keyword
==============
case 1:
import java.io.*;
class Test
{ void studentInfo()throws FileNotFoundException
{ System.out.println("Veera information....");
FileInputStream fis = new FileInputStream("abc.txt");
}
void hod()throws FileNotFoundException
{ studentInfo();
}
void principal()
{ try{hod();}
catch(FileNotFoundException e)
{System.out.println("file is not present...");}
}
void officeBoy()
{ principal();
}
public static void main(String[] args)
{ Test t = new Test();
t.officeBoy();
}
}
case 2:
import java.io.*;
class Test
{ void studentInfo()throws FileNotFoundException
{ System.out.println("Veera information....");
FileInputStream fis = new FileInputStream("abc.txt");
}
void hod()throws FileNotFoundException
{ studentInfo();
}
void principal()throws FileNotFoundException
{ hod();
}
void officeBoy()throws FileNotFoundException
{ principal();
}
public static void main(String[] args) throws FileNotFoundException
{ Test t = new Test();
t.officeBoy();
}
}
If the main throws the exception then JVM is responsible to handle the exception.
Observation: The method can throws parent & child exeptions but it is not
recommanded.
void m2()throws InterruptedException,Exception
{
}
ex-5:
import java.io.*;
class Test
{ void m2()throws FileNotFoundException,InterruptedException
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()throws InterruptedException
{ try
{ m2();
}
catch(FileNotFoundException f)
{ f.printStackTrace();
}
}
public static void main(String[] args)
{ Test t = new Test();
try
{ t.m1();
}
catch (InterruptedException i)
{ i.printStackTrace();
}
}
}
In above example the exception raised in m3() method but it is not handled so it
is propagated to m2() method.
Here the m2() method is not handled exception so it is propagated to m1().
In above example m1() is handled exception.
Note: only the unchecked Exceptions are propagated automatically but not checked.
The checked exceptions are propagated using throws keyword.
throw
import java.util.*;
class Test
{ static void validate(int age)
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new ArithmeticException("your not eligible try after
sometime...");
}
}
public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int age = s.nextInt();
Test.validate(age);
}
}
E:\>java Test
please enter your age
12
Exception in thread "main" java.lang.ArithmeticException: your not eligible try
after sometime...
Userdefiend exception
Note: using throw keyword we can throw predefined exceptions & userdefined
exception.
But throwing predefined exceptions are not recommanded because predefined
exceptions are having fixed meaning.