Saturday, November 16, 2013

Java user defined Exception Example

Write a program that calls a method to divide two integers entered from the keyboard and throws an user defined exception of type ArithmeticException when trying to divide by zero.The program should take the user input from the console and based on the condition should throw an user defined exception which prints a message.

Sample Output :

Enter the first number:
10
Enter the second number:
0
Exception Occurred :Trying to divide 10/0 .Division by zero is not allowed.


Solution: 

 
import java.util.Scanner;

public class UserDefinedException {
 
 public static void main(String args[]){
  //Creating scanner object
  Scanner input=new Scanner(System.in);
  int a=0;
  int b=0;
  
  try{
   System.out.print("Please enter first integer: ");
   a=input.nextInt();
   System.out.print("Please enter second integer: ");
   b=input.nextInt();
    
   int result=divide(a,b);
   System.out.printf("Result: %d/%d = %d\n",a,b,result);
    
  }
  catch(Excp ae){
   System.out.println(ae.getMessage());
  }
 }
 
 //Divide function
 static public int divide(int a,int b) throws Excp {
  if(b==0){
   String s = String.format(
     "Exception Occurred :Trying to divide %d/%d .Division by zero is not allowed",a,b);
   throw new Excp(s);
  }
  return a/b;
 }
}

class Excp extends Exception {
 public Excp(){}
 public Excp(String s){
  super(s);
 }
}

No comments:

Post a Comment