1) Program
to accept a number from the user and throw an exception if the number is not an
even number.
Code:
import java.lang.*;
import java.io.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class EvenException
{
public static void main(String args[])throws IOException
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
int number;
try
{
System.out.println("Enter the Number = ");
number=Integer.parseInt(b.readLine());
if(number%2!=0)
{
throw new MyException("The Number is not an even number");
}
}
catch(MyException e)
{
}
}
}
Output:
C:\Program Files\Java\jdk1.6.0_07\bin>javac EvenException.java
C:\Program Files\Java\jdk1.6.0_07\bin>java EvenException
Enter the Number =
5
MyException: The Number is not an even number
2) ArithmeticException
Demo programs.
Code:
class ArithmeticException
{
public static void main(String args[])
{
int x,y,z,w;
x=10;y=20;z=20;
try
{
w=x/(y-z);
System.out.println("Result="+w);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
}
}
3) ArrayStoreException
Demo programs
Code:
class ArrayStoreException
{
public static void main(String args[])
{
try
{
int arr[]=new int[5];
arr[0]=args[0];
}
catch(ArrayStoreException Ase)
{
System.out.println("\n Wrong data type stored");
}
}
}
4) Demo
program on Exception.
Code:
class ExceptionDemo
{
public static void main(String args[])
{
int x,y,z,w;
x=10;y=20;z=20;
try
{
w=x/(y-z);
System.out.println("Result="+w);
}
catch(Exception e)
{
System.out.println("Exception ="+e);
}
}
}
5) Exception
demo
Code:
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5;
int y=1000;
try
{
float z=(float)x/(float)y;
if(z<0 .01="" span="">0>
{
throw new MyException("Number small");
}
}
catch(MyException e)
{
System.out.println("\nCaught my Exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("\nI am always here");
}
}
}
6)
To implement Program for Nested Try Demonstration
Code:
class NestedTry
{
public static void main(String args[])
{
try
{
int x=args.length;
int y=50/x;
System.out.println("\nCommand line arguement count="+x);
try
{
if(x==1)
{x=x/(x-x);}
if(x==2)
{
int arr[]={5,10,15,20};
arr[20]=100;
}
}
catch(ArithmeticException Ae)
{
System.out.println("\nDivide by zero");
}
catch(ArrayIndexOutOfBoundsException AIOB)
{
System.out.println("\nDivide by zero");
}
}
catch(ArithmeticException ae)
{
System.out.println("\nZero command line arguement");
}
}
}
Output:
Zero command line arguement
No comments:
Post a Comment