Exception handling
Exception handling
st-1
st-2
st-3 exception raised
st-4
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
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.
IOException,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);
//errors :
The exception are occurred due to two 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
class Test
{ public static void main(String[] args)
{ int[] a = new int[1000000000];
}
}
java.lang.OutOfMemoryError: Java heap space
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 the exception raised in the try block, the corresponding catch
block executed.
Disadvantages:
1. program terminated abnormally.
2. rest of the application not 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);
}
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 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
5
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
Day-2 Exception Handling
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");
int num = s.nextInt();
try
{ 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:
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");
int num = s.nextInt();
try
{ 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");
}
System.out.println("Rest of the application....");
}
}
The 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: Declare the resource using try block, once the try block is completed the
resource is automatically released.
how it releases automatically means, it internally uses AutoCloseable.
void close() throws Exception
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 exception, 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 exception, so catch block required.
FileNotFoundException: reading the data from the file
IOException: exception thrown from implicit call to close().
case 3:By using try block it is possible to declare more than one resource but
every resource is separated with a semicolon.
try(Scanner s = new Scanner(System.in);
FileInputStream fis = new FileInputStream("abc.txt"))
{ //some code here
}
in multiple resources, if at least one resource throws an exception then catch is
mandatory.
case 1:The developer can print the exceptions msg in three ways,
1) toString()
2) getMessage()
3) printStackTrace()
class Test
{ void m3()
{ try{ System.out.println(10/0); }
catch(ArithmeticException ae)
{ System.out.println(ae.toString());
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)
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.
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 ()
{
}
}
finally
try
{
connection open
tx1
tx2
}
catch ()
{
}
conection close
To close the connection both normal & abnormal cases use finally block because the
finally block code executed both normal & abnormal cases.
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("try");
}
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);
}
}
import java.util.Scanner;
class Test
{
void disp(){}
public static void main(String[] args)
{
Test t = new Test();
t.disp();
t=null;
t.disp(); java.lang.NullPointerException
String str= null;
System.out.println(str.length()); java.lang.NullPointerException
}
}
throws keyword
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();
}
}
Note: unchecked exceptions are automatically propagated. But checked exceptions are
propagated using throws keyword.
ex5:
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 ie){ie.printStackTrace();}
}
}
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
try
catch
finally
throws
throw
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
ArithmeticException
System.out.println(10/0);
StringIndexOutOfBoundsException
System.out.println("ratan".cahrAt(12));
ArrayIndexOutOfBoundsException
int[] a = {10,20,30}
System.out.println(a[8]);
java.lang.NegativeArraySizeException
int[] a = new int[-5];
InterruptedException
Thread.sleep(1000)
FileNotFoundException
FileInputStream fis = new FileInputStream("abc.txt");
NullPointerException:
String str = null;
System.out.println(str.length());
NumberFormatException:
Integer i = new Integer("10"); // valid
Integer i = new Integer("ten"); // NFE