Exception Handling in Java Day-2
Exception Handling in Java Day-2
Revision
• An Exception is a run-time error
• To monitor code for exceptions must part of try
block.
• The catch receives exceptions. A catch is not
called; thus execution does not return to the
point at which the exception was generated.
• Rather, execution continues after the catch block.
• The type of exception must match the type
specified in a catch.
Exception Handling
class Exp {
static void genExp() {
int []num=new int[4];
System.out.println("\n Before exception");
num[7]=10; //Exception Generated here
System.out.println("\n After exception");
}
}
class DemoExp
{
public static void main(String args[])
{
try
{
Exp.genExp(); // Static method ,so need to create object
}
catch(ArrayIndexOutOfBoundsException ex) //Exception caught here
{
System.out.println("\n Index Out Of Bounds");
}
System.out.println("\n After Exception");
}
}
Types of Exceptions
Find the output
class TestExp
{
public static void main(String args[])
{
int []num=new int[6];
try
{
System.out.println("\n Before Exception");
num[7]=10;
System.out.println("\n After Exception");
}
catch(ArithmeticException ex)
{
System.out.println("\n Index Out Of Bounds");
}
System.out.println("\n After Exception");
}
}
Handle Errors Gracefully
class TestExp
{
public static void main(String args[])
{
int []num1={4,8,16,32,64,128};
int []num2={2,0,4,4,0,8};
for(int i=0;i<num1.length;i++)
{
try
{
System.out.println(num1[i]+"/"+num2[i]+" is "+num1[i]/num2[i]);
} C:\prac-java>java TestExp
catch(ArithmeticException ex)
{
4/2 is 2
System.out.println("\n can't divide by zero");
} can't divide by zero
} 16/4 is 4
} 32/4 is 8
}