0% found this document useful (0 votes)
48 views

Exception Handling

java

Uploaded by

Ashok Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Exception Handling

java

Uploaded by

Ashok Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 20

Exception handling

st-1
st-2
st-3 exception raised
st-4

In application whenever the exception occurred,


1. Program terminated abnormally.
2. Rest of the application is not executed.

There are two ways to handle the exception,


a. try-catch
b. throws

once we handle the exception


1. Program terminated normally.
2. Rest of the application is executed.

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); //AE

int[] a = {10,20,30};
//System.out.println(a[6]);
java.lang.ArrayIndexOutOfBoundsException:

//System.out.println("ratan".charAt(12));
StringIndexOutOfBoundsException

//int[] arr = new int[-6];


java.lang.NegativeArraySizeException

System.out.println("rest of the application");


}
}

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)throws
InterruptedException,FileNotFoundException
{ System.out.println("ratan");
//Thread.sleep(1000);

FileInputStream fis = new FileInputStream("abc.txt");

System.out.println("rest of the application...");


}
}

Note: Whether it is a checked Exception or unchecked exception exceptions are


raised at runtime but not compile time.
Note :The checked exceptions are safe beacue the compiler will give some
information about the exception at compile time itself.

//errors :
The exception are occurred due to the fallowing reasons

a. Developer mistakes
b. End-user input mistakes.
c. network Connections.
But errors are caused due to lack of system resources.
StackOverFlowError, OutOfMemoryError …………etc

It is possible to handle the exceptions by using try-catch blocks or throws keyword


but it is not possible to handle the errors.

class Test
{ public static void main(String[] args)
{ int[] a = new int[1000000000];
}
}
java.lang.OutOfMemoryError: Java heap space

Error is an un-checked type exception.

Exception handling keywords:


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

There are two ways to handle the exceptions in java.


1) By using try-catch block.
2) By using throws keyword

Exception handling by using try–catch blocks:


Syntax:
try
{ exceptional code : it may or may not raise an exception
}
catch (Exception_Name reference_variable)
{ logics run if an exception raised in try block.
}
ex-1 : Whenever exception raised in the try block, the corresponding catch block
executed.

Application without try-catch blocks


class Test
{ public static void main(String[] args)
{ System.out.println("ratan");
System.out.println(10/0);
System.out.println("rest of the application");
}
}
E:\>java Test
ratan
Exception : ArithmeticException: / by zero

Disadvantages:
1. program terminated abnormally.
2. rest of the application not executed.

Application with try-catch blocks:


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();
try
{ System.out.println(10/num);
}
catch (ArithmeticException ae)
{ System.out.println(10/5);
}
System.out.println("Rest of the application.....");
}
}
E:\>java Test
Enter a number:
0
2
Rest of the application.....

Advantages:
1. Program terminated normally
2. 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");
}
}
E:\sravya>java Test
sravya
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");
}
}
E:\sravya>javac Test.java
Test.java:4: 'try' without 'catch' or 'finally' or resources

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:
If the exception raised in other than try block it is always abnormal termination.
In below example exception raised in catch block hence program is terminated
abnormally.
try
{ System.out.println(10/0);
}
catch(ArithmeticException e)
{ System.out.println(10/0);
}

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

Category-1 : try with multiple catch blocks


case 1 :
import java.util.*;
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(InputMismatchException i)
{ System.out.println("Enter valid data....only integers");
}
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
catch(StringIndexOutOfBoundsException e)
{ System.out.println("nareshit");
}
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("Ratanit..."+e);
}
System.out.println("Rest of the application....");
}
}

case 3: The catch block order must be child to parent.


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));
}
//child to parent
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
catch(Exception e)
{ System.out.println("nareshit..."+e);
}
System.out.println("Rest of the application....");
}
}

case 4: Parent to child :


import java.util.*;
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("nareshit");
}
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
System.out.println("Rest of the application....");
}
}
in above case the parent can handle all exceptions then child no use.
error: exception ArithmeticException has already been caught

Category-2 pipe symbol java 7-version

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 3: mixing of both checked & uncheked


catch(FileNotFoundException| ArithmeticException a)

case 4: Invalid : not possible to take both parent & child


catch(Exception | ArithmeticException a)

Category-3 try-with resources java 7

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. Closes this resource, relinquishing any underlying resources. This method is
invoked automatically on objects managed by the try-with-resources statement.

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);
}
}
}
if the resource is not throwing an excpetions so catch block not required.

case 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()

FileNotFoundException is a child cls of IOException so taking catch block of parent


class is good.

case 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.

Category-4 posibilities of try-catch

case 1:
try{
}
catch (){
}

case 2:
try{
}
catch (){
}
fsdfsdf
sdfsdfsdf
try{
}
catch (){
}

case 3:
try{
}
catch (){
}
catch (){
}

case 4:
try
{ try
{
}
catch ()
{
}
}
catch ()
{
}

case 5:
try
{
}
catch ()
{ try
{
}
catch ()
{
}
}

case 6:
try
{ try
{
}
catch ()
{
}
}
catch ()
{ try
{
}
catch ()
{
}
}

Category-5 printing Exception information

case 1:The developer can print the exceptions msg in three ways,
1) printing reference variable : toString()
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)

case 2: if we are not handled exception so The JVM Internally uses


printStackTrace() method to print exception information.

finally
=======
//Application without finally
try
{ connection open
tx1
tx2
}
catch ()
{
}
conection close

case 1: connection open : both trasaction are success : normal termination :


connection is closed
case 2: connection open : first transaction is fail : catch block is matched :
normal termination : connection is closed
case 3: connection open : second transaction is fail: catch block is not
mateched :abnormal termination : connection is not closed

To close the connection both normal & abnormal cases use finally block because the
finally block code executed both normal & abnormal cases.

//Application with finally


try
{ connection open
tx1
tx2
}
catch ()
{
}
finally{
conection close
}

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

In two cases finally block won’t be executed


Case 1: whenever the control is entered into try block then only finally
block will be executed otherwise it is not executed
class Test
{ public static void main(String[] args)
{ System.out.println(10/0);
try
{ System.out.println("ratan");
}
finally
{ System.out.println("finally block");
}
System.out.println("rest of the code");
}
}

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);
}
}

only try : Invalid


only catch : Invalid
only finally : Invalid

try-catch : Valid
try-finally : Valid
try-catch-catch : Valid

try-catch-finally : Valid
try-catch-catch-finally : Valid
catch-finally : Invalid

try-finally-finally : Invalid
try-finally-catch : Invalid
try-catch-finally-catch : Invalid
catch-try : Invalid

throws keyword
==============

There are two ways to handle the exceptions,


a. using try-catch
b. using throws

case 1:
class Test
{ void studentDetails() throws InterruptedException
{ System.out.println("suneel babu is sleeping");
Thread.sleep(3000);
System.out.println("do not disturb sir......");
}
void hod()throws InterruptedException
{ studentDetails();
}
void principal()
{ try
{ hod();
}
catch(InterruptedException ie)
{ ie.printStackTrace();
}
}
void officeBoy()
{ principal();
}
public static void main(String[] args)
{ Test t = new Test();
t.officeBoy();
}
}

case 2:
class Test
{ void studentDetails() throws InterruptedException
{ System.out.println("suneel babu is sleeping");
Thread.sleep(3000);
System.out.println("do not disturb sir......");
}
void hod()throws InterruptedException
{ studentDetails();
}
void principal()throws InterruptedException
{ hod();
}
void officeBoy()throws InterruptedException
{ principal();
}
public static void main(String[] args)throws InterruptedException
{ Test t = new Test();
t.officeBoy();
}
}

If the main throws the exception then JVM is responsible to handle the exception.

ex 3: One method can throws multiple exceptions


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()
{ try
{ m2();
}
catch(FileNotFoundException | InterruptedException f)
{ f.printStackTrace();
}
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}

ex-4: use the root cls to throws all exceptions.


import java.io.*;
class Test
{ void m2()throws Exception
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()
{ try
{ m2();
}
catch(Exception f)
{ f.printStackTrace();
}
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}

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();
}
}
}

ex-6: Exception Propagation.


class Test
{ void m3()
{ System.out.println(10/0);
}
void m2()
{ m3();
}
void m1()
{ try
{ m2();
}
catch(ArithmeticException ae)
{ System.out.println("Exception handled...");
}
}
public static void main(String[] args)
{ new Test().m1();
}
}

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.

Note: using throws can we deligate unchecked exception?


yes possible but not recommanded, because unchecked exceptions are
automatically propagated.

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 1: no exception in above example.


1,2,3,4,5,6,15,16,17,18 Normal termination.

case 2: exception raise in st-2


1 Abnormal termination

case 3: exp raised in st-3 catch is matched.


1,2,9,10,11,12,15,16,17,18 normal termiatio

case 4: exp raised in st-4 catch is not matched.


1,2,3,15,16 abrnormal termination

case 5: exp raised in st-5 catch is matched.


1,2,3,4,7,8,15,16,17,18 normal termination

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

case 7: exp raised in st-16


case 8: exp raised in st-18

throw

ex: here we are throwing predefiend exception which is not recommanded.


Because the predefined exceptions are having fixed meaning.

import java.util.*;
class Test
{ static void validate(int age)
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new ArithmeticException("not eligible for marriage");
}
}
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);
}
}

Userdefiend exception

There are two types of userdefined exceptions,


1. userdefined checked exception.
a. default cons : Exception without description
b. params cons : Exception with description.
class InvalidAgeException extends Exception
{
}

2. userdefined un-checked exception


a. default cons : Exception without description
b. params cons : Exception with description.
class InvalidAgeException extends RuntimeException
{
}

ex-1: userdefined unchecked exception : with default constructor : without


discription.
step 1: create the exception
class InvalidAgeException extends RuntimeException
{ //default cons
}

step 2: use that exception in our project.


import java.util.*;
class Test
{ static void validate(int age)
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new InvalidAgeException();
}
}
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);
}
}

ex-2: userdefined unchecked exception : with params constructor : with description.

step 1: create the exception


class InvalidAgeException extends RuntimeException
{ InvalidAgeException(String msg)
{ super(msg);// calling the parent constructor by passing our
information.....
}
}

step 2 : use the exception in our project


import java.util.*;
class Test
{ static void validate(int age)
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new InvalidAgeException("u r not eliible to mrg");
}
}
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);
}
}

ex: userdefined checked exception : with params constructor : with description.


step 1: create the exception
class InvalidAgeException extends Exception
{ InvalidAgeException(String str)
{ super(str);
}
}

step 2 : use the exception in our project


import java.util.*;
class Test
{ static void validate(int age) throws InvalidAgeException
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new InvalidAgeException("u r not eliible to mrg");
}
}
public static void main(String[] args) throws InvalidAgeException
{ Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int age = s.nextInt();
Test.validate(age);
}
}

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.

try : it contains exceptional code it may or maynot raise an


exception.
catch : these logics are executed when exception raised in try block.
finally : These logics are executed both normal & abnormal cases.
throws : To delegate the responsibility of exception handling to
caller methods.
throw : Used to throw the exception.

Assignment : when we will get StackOverflowError.


class Test
{ void m2()
{ System.out.println("m2 method");
m1();
}
void m1()
{ m2();
System.out.println("m1 method");
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}

when we call the method that method name stored in stack memroy
once the method is completed it is destoryed from stack.
............StackOverflowError
m2
m1
m2
m1
m2
m1
main

Assignment : java.lang.NoClassDefFoundError vs java.lang.ClassNotFoundException

Assignment : can we create the userdefined errors.


yes : write the example
no : no example

Assignment: create the unchecked exception.


file-1 : TooYoungException : wihtout description
file-2 : TooOldException : with description : "your not
eligible to mrg"
file-3 : In Application Take the input from end user
age <18 : throw TooYoungException
age >35 : throw TooOldException
age b/w 18 to 35 : eligible for mrg.

ArithmeticException
System.out.println(10/0);

StringIndexOutOfBoundsException
System.out.println("ratan".charAt(2)); //t
System.out.println("ratan".charAt(12));

ArrayIndexOutOfBoundsException
int[] a = {10,20,30}
System.out.println(a[2]); // 30
System.out.println(a[8]);

NegativeArraySizeException
int[] a = new int[5]; //valid
int[] a = new int[-5]; //invalid

InterruptedException
Thread.sleep(1000)
FileNotFoundException
FileInputStream fis = new FileInputStream("abc.txt");

ex: NullPointerException :if the object location is null but if we are trying to
access the methods it will generate Exception.
class Test
{ public static void main(String[] args)
{ String str1 = "ratan";
System.out.println(str1.length());

String str2 = null;


System.out.println(str2.length());
}
}

ex:
class Test
{ void m1()
{ System.out.println("m1 method");
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();

t = null;

t.m1(); //java.lang.NullPointerException
}
}

NumberFormatException:
Integer i = new Integer("10"); // valid
Integer i = new Integer("ten"); // NFE

You might also like