Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

Exception Handling

Exception Handling
• Exception handling is one of the powerful
mechanism provided in JAVA.
• It provides mechanism to handle exceptions
so that normal flow of application can be
maintained.
• The java.lang.Throwable class is the root class
of Java Exception hierarchy which is inherited
by two subclasses:
• Exception and Error.
Exception Handling
Exception :
An exception is a problem that arises during
the execution of a program.
Exception interrupts the normal flow of
program.
Exception Handling: Exception Handling is a
mechanism to handle exceptions.
Advantage of Exception Handling
• To maintain the normal flow of execution
• e.g.
Statement 1 ;
Statement 2;
Statement 3; without exception handling, rest of the code i.e.
Statement 4 ; statements 6 to 10 will not be executed.
Statement 5; ----error
Statement 6;
Statement 7; using exception handling, rest of the code i.e.
Statement 8; statements 6 to 10 will be executed.
Statement 9; advantage
Statement 10;
Common Java Exceptions
Sr. Exception Cause of Example
No. exception
01 ArithmeticException while int a=10;
performing int b=0;
arithmetic int c;
operations such c=a/b;
as divide by zero //ArithmeticException
…….
…….
02 ArrayIndexOutOfBoundsException Caused by bad int a[]=new int[5];
array index a[10]=40;
//ArrayIndexOutOfBou
ndsException
Common Java Exceptions
Sr. Exception Cause of exception Example
No.
03 NullPointerException Caused by String s=null;
referencing a null System.out.println(“string
object. length=“+s.length(););
//NullPointerException

04 NumberFormatException Caused when String s=“abc”;


conversion between int i=Integer.parseInt(s);
string and number //NumberFormatException
fails.

05 StringIndexOutOfBoundsE Caused when String s=“abc”;


xception program attempts to char ch;
access non- existent ch=s.charAt(10);
Character position //StringIndexOutOfBoundsExc
in string. eption
Exception Handling
Exception Handling keywords
Exception Handling is managed by 5 keywords.
1)try
2)catch
3)finally
4)throw
5)throws
try_catch block
try block :try block contains the statements that may generate the
exception.
catch block: catch block contains the statements to process the
exception.
Syntax:
try
{
Statements ; //generate an exception
}
catch(Exceptionclass object_name)
{
Statements; //process an exception
}
Program without exception handling
class abc
{
public static void main(String args[])
{
int a,b,c1,c2;
a=10;
b=0;
d=2;
c1=a/b;
System.out.println(“C1=“+c1);
c2=a/d;
System.out.println(“c2=“+c2);
}
}

 Java abc.java
 error:java.lang.ArithmeticException : / by Zero
Program using exception handling
class abc //System.out.println(“divide by zero”);
{ }
public static void main(String args[])
{ c2=a/d;
int a,b,c1,c2,d; System.out.println(c2);
a=10;
b=0; }
d=2; }
try
{
c1=a/b;
System.out.println(“C1=“+c1);
}
catch(ArithemeticException e)
{
System.out.println(e);
//Or
//System.out.println(e.getMessage());
//Or
Program to handle ArrayIndexOutOfBoundsExcxeption

class abc
{
public stativ void main(String args[])
{
Int a[]=new int[5];
try
{
a[7]=10;
System.out.println(“a*7+=“+a*7+);
}catch(ArrayIndexOutOfBoundsExcxeption e)
{
System.out.println(e);
}
}
}
Program to handle ArrayIndexOutOfBoundsExcxeption
class abc C:\tyif> java abc.java
{
public static void main(String args[]) java.lang.ArrayIndexOutOfBoundsExcept
{ ion :7
Int a[]=new int[5];
try Output of remaining code
{
a[7]=10;
System.out.println(“a*7+=“+a*7+);
}
catch(ArrayIndexOutOfBoundsExcxeption e)
{
System.out.println(e);
}

//remaining code………………..

}
}
Program to handle NullPointerExcxeption
class abc C:\tyif> java abc.java
{
public static void main(String args[]) java.lang. NullPointerExcxeption
{
String str=null; Output of remaining code
int len;
try
{
len=str.length();
System.out.println(“string length=“+len);
}
catch(NullPointerExcxeption e)
{
System.out.println(e);
}

//remaining code………………..

}
}
Program to handle NumberFormatException
class abc C:\tyif> java abc.java
{
public static void main(String args[]) java.lang. NumberFormatException:For input string
{ :“abc”
String str=“abc”;
int i; Output of remaining code
try
{
i=Integer.parseInt(str);
}
catch(NumberFormatException e)
{
System.out.println(e);
}

//remaining code………………..

}
}
Program to handle StringIndexOutOfBoundsException
class abc2 C:\tyif> java abc.java
{
public static void main(String args[]) java.lang. StringIndexOutOfBoundsException:string
{ index of out of range :5
String str="abc";
char ch; Output of remaining code
try
{
ch=str.charAt(5);
}
catch(StringIndexOutOfBoundsExce
ption e)
{
System.out.println(e);
}

//remaining code………………..

}
}
Multiple catch statements
---Multiple catch statements are used to handle different types of exception.
--When an exception in try block is generated, java treats multiple catch
statements like cases in a switch statement.
try .
{ .
Statements; .
} catch(Exception_Type n object)
catch(Exception_Type1 object) {
{ Statements;
Statements; }
}
catch(Exception_Type2 object)
{
Statements;
}
Multiple catch statements
• Multiple catch statements are used to handle different types of exception.
• Syntax:
try
{
Statements;
}
catch(Exception_Type1 object)
{
Statements;
}
catch(Exception_Type1 object)
{
Statements;
}
Program using multiple catch statement

class abc //remaining code………………..


{
public static void main(String args[]) }
{ }
Int a=10,b=0,c;
int a[]=new int[6];
try
{
c=a/b;
a[6]=90;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException
e)
{
System.out.println(e);
finally block
• finally block is executed after try -catch block
and before the code following try-catch block.

• finally block is executed regardless of whether


exception is thrown or not.
Syntax
try
{
Statements;
}
catch
{
Statements;
}
finally
{
Statements;
}
program
class abc
{
public static void main(String args[]) finally
{ {
int a=10,b=0,c; System.out.println(“finally block
try executed”);
{ }
c=a/b;
System.out.println(c); //remaining part of code;
}
} }
catch(ArithemeticException e)
{
System.out.println(e);
}
throw statement
• throw statement is used to throw exception
explicitly.
• To throw exception explicitly, first we have to
create object of that exception type.
• Syntax:
Exceptionclass obj;
Obj=new exceptionclass();
throw obj;
throws statement
• ‘throws’ statement is used when we know
that method may cause exception, but there is
no exception handling mechanism within the
method. Here callers of the method guard
themselves against the exception.
• Syntax:
Return type method_name(arg list)throws
Exception1,exception2,….
{
Statements;
}
class abc
{
void cal() throws ArithemeticException
{
int a=10,b=0,c;
c=a/b;
System.out.println(c);
}
}
class Demo
{
public static void main(String args[])
{
abc a=new abc();
try
{
a.cal();
}
catch(ArithemeticException e)
{
System.out.println(e);
}
}
User Defined Exception
• User defined exception is an exception which is
created by defining a subclass by inheriting built-
in Exception class and then by throwing an object
of user defined exception class from try-catch
block.
• Syntax to define class :
Class user_defined_ exception_ classname extends
Exception
{
Statements;
}
• Syntax to create object of user defined
Exception:
Classname obj=new classname(“string”);
• Syntax to throw user defined exception:
throw obj;
steps for using user defined exception in java program

1. Create user defined exception class by extending


Exception class.
2. Every user defined exception class must contain
a parameterized constructor with string as a
parameter.
3. String parameter represents nature of error
message.
4. parameterized constructor of every user defined
exception must call parameterized constructor
of its super class i.e. Exception class by using
‘super’ keyword.
Program to throw user defined exception by accepting
a number from user and throw an exception if number
is negative number.
class MyException extends try
Exception {
{ if(n<0)
{
MyException(String msg)
MyException obj=new MyException(“number
{
is negative”);
super(msg); throw obj;
} }
} catch(MyException m)
class Demo {
{ System.out.println(m);
public static void main(String args[]) }
{ }
}
int n;
n=Integer.parseInt(args[0]);
Program to accept password from user and throw
authentication failure exception if password is incorrect.
class MyException extends Exception try
{ {
MyException(String msg) if(password.equals(user_pass))
{ {
super(msg); Ssytem.out.println(“correct password”);
} }
} else
{
class Demo MyException obj=new
{ MyException(“authentication failure”);
public static void main(String args[]) throw obj;
{ }
String password=“abc”; }
String user_pwd; catch (MyException m)
user_pwd=args[0]; {
Sytem.out.println(m);
}
}
}
Program to accept number from user and throw an exception
if number is not even number.
class MyException extends Exception else
{ {
MyException(String msg) MyException obj=new
{ MyException(“number is odd”);
super(msg); throw obj;
} }
} }
catch (MyException m)
class Demo {
{ Sytem.out.println(m);
public static void main(String args[]) }
{ }
int n1; }
n1=Integer.parseInt(args[0]);
try
{
if(n1%2==0)
{
System.out.println(“number is even”);
}
Shivnath Sir
• Exception can be handled but not error
• 5 keywords to handle it
• Identify the part that may cause Exception and
then put part in try catch
• Every type exception has a class
• When exception is thrown JVM createsobject
Specific catch exception
Exception object will b store in
reference variable in catch
Like if else respectiv match is executed
Single try can have Multiple catch
• Only one catch block will get executed at a
time
• Control never goes back
• Program has or doesn’t has finally block
executes (Database Connection problem)
• One cannot write finally without try block
There can b
• Try and finally
• Try and catch
• Try catch finally
• Find all types of inbuilt exception when r they
thrown
All exception are child of Exception
class
• Try can have multiple catch
• Exception is parent of all exception whethr it is
runtime so one can define a common
exception object
Multiple exceptin at a time using
common handler
User Define Msg
• Handle individual Exceptions
FCFS Exception
Show actual msg error
message
printStacktrace
toString (Obj class)print name of class,
hexaval hashcode-SOP ae call tostring
getMessage & printStackTrace method
in EH
• Order of catch is changed
• Catch(Exception)//will handle all
• {
• }
• Catch(AE)
• {
• }
Sequence child to parent
• Try
• {
• }
• Catch(Child)
• {}
• Catch(Parent)
• {}
Single Handler- use pipe to separate
different exception types , refernce var
• Can handle anywill bebut
count single
they must b not
parent child relation
• Ex:
• AE,E (invalid parent )
• AE,NullPtr(valid)sssss
No inheritance child – parent relation
User Defined Exception
Nested try catch block
Checked Unchecked Exception
Unchecked Exception
Checked File not found Compiler force
to handle
Try with resources file, DB
connection establish
explicitly
Implicit in try as arg

You might also like