0% found this document useful (0 votes)
2 views18 pages

Exception handling

The document discusses exception handling in programming, outlining the importance of managing exceptions to ensure normal program termination. It categorizes exceptions into checked, unchecked, and errors, explaining how to handle them using try-catch blocks and the throws keyword. Additionally, it covers advanced topics such as multiple catch blocks, try-with-resources, and printing exception information.

Uploaded by

kiran
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
2 views18 pages

Exception handling

The document discusses exception handling in programming, outlining the importance of managing exceptions to ensure normal program termination. It categorizes exceptions into checked, unchecked, and errors, explaining how to handle them using try-catch blocks and the throws keyword. Additionally, it covers advanced topics such as multiple catch blocks, try-with-resources, and printing exception information.

Uploaded by

kiran
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 18

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 excpetion,


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

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 because the compiler will give some
information about the exception at compile time itself.

//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

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 the 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:


class Test
{ public static void main(String[] args)
{ System.out.println("ratan");
try {
System.out.println(10/0);
}
catch (ArithmeticException ae)
{ System.out.println(10/2);
}
System.out.println("rest of the application");
}
}
E:\>java Test
ratan
5
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 executed.
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 block declaration is 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
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

Category-1 : try with multiple catch blocks


case 1 :
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 (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");
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....");
}
}

case 4: Parent to child :


//parent to child
catch(Exception e)
{ System.out.println("nareshit");
}
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
in above case the parent can handle all exceptions then no use of child.
error: exception ArithmeticException has already been caught

Category-2 pipe symbol java 7v

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 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: 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().

FileNotFoundException is a child class of IOException, so taking catch block of the


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

Category-4 printing Exception information

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)

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


printStackTrace() method to print exception information.

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

Category-5 nested 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 ()
{
}
}

finally
try
{
connection open
tx1
tx2

}
catch ()
{
}
conection close

case 1: connection open : both trasaction are success : normal : 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.

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

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

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

Note : unchecked exceptions are automatically propagated,


But checked exceptions are propagted using throws keyword.

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.

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

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

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: userdefined unchecked exception : with default constructor : without


discription.
step 1: create the exception
class InvalidAgeException extends RuntimeException
{ //deault 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: userdefined unchecked exception : with params constructor : with discription.


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

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


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

try
catch
finally
throws
throw

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

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 : can we create the userdefined errors.


yes : write the example
no : no example

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

Test t = new Test();


t.wish();
t=null;
t.wish();

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

You might also like