You are on page 1of 5

Exercise 21

1. Write a program that throws an arithmetic exception and catch it


using exception handling.
Ans.
import java.util.*;
class Ex21p1
{
public static void main(String args[])
{
int a,b,c;
a=25;
b=0;
try
{
c=a/b;
System.out.println("a/b :" +c);
}
catch(ArithmeticException e)
{
System.out.println("a/b is not possible, beacuse b is zero");
}

}
}
2. Write a program that throws an arithmetic exception or a input
type mismatch exception and catch these using multiple catch
statements.
Ans.
import java.util.*;
class Ex21p2
{
public static void main(String args[])
{
Scanner sc =new Scanner(System.in);
int a,b,c;

try
{
System.out.println("Enter the value of a");
a=sc.nextInt();
System.out.println("Enter the value of b");
b=sc.nextInt();
c=a/b;
System.out.println("a/b :" +c);
}
catch(ArithmeticException e)
{
System.out.println("a cannot divide b, beacuse b is
zero");
}
catch(InputMismatchException e)
{
System.out.println("input value is not an integer");
}

}
}
3. Write a program that throws an arithmetic exception or a input
type mismatch exception and catch these using nested try- catch.
Ans.
import java.util.*;
class Ex21p3
{
public static void main(String args[])
{
Scanner sc =new Scanner(System.in);
int a,b,c;

try
{
try
{
System.out.println("Enter the value of a");
a=sc.nextInt();
System.out.println("Enter the value of b");
b=sc.nextInt();
c=a/b;
System.out.println("a/b :" +c);
}

catch(ArithmeticException e)
{
System.out.println("caught by outer block");
System.out.println("a cannot divide b, beacuse b
is zero");
}
}
catch(InputMismatchException e)
{
System.out.println("caught by inner
block");
System.out.println("input value is not an integer");
}

}
}
4. Write a program in which a method throw an exception that
should be handled by calling method. Demonstrate the working
by calling this method in main class .
Ans.
import java.util.*;
class Ex21p4
{
public static void main(String args[])
{
try
{
test();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Given a wrong index");

}
static int test() throws ArrayIndexOutOfBoundsException, InputMismatchException
{
int a[]={1,2,4,5,0};
Scanner sc= new Scanner(System.in);
System.out.println("Enter an index value");
int i =sc.nextInt();
return a[i];
}
}

You might also like