User defined exception example

Exception Handling: user defined exception example
package com.ram;

import java.io.BufferedReader;
import java.io.InputStreamReader;

class MyException extends Exception{
 private static final long serialVersionUID = 1L;
 String except;

 public MyException(String str){
  except = str;
 }

 public String toString(){
  return "This is from MyException ..."+except;
 }
}

public class ExceptionHandlingExample3 {
 public static void main(String[] args){
  int a, b, c=0;

  try{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

   System.out.print("Enter value for a :: ");
   a = Integer.parseInt(br.readLine());

   System.out.print("Enter value for b :: ");
   b = Integer.parseInt(br.readLine());

   if(b==0){
    throw new MyException("Dividing by zero will result in exception ... enter a value other than 0 for 'b'");
   }else{
    c = a / b;
   }

   System.out.println("Value of c is :: "+c);
   
  }catch(MyException mye){
   System.out.println("Catching MyException ...");
   System.out.println(mye);
  }
  catch(Exception e){
   System.out.println("Other exceptions ... "+e);
  }
 }
}

 
 
Execute ExceptionHandlingExample3 class and user would be prompted to enter two values.
Enter value for a :: 10
Enter value for b :: 0
Catching MyException ...
This is from MyException ...Dividing by zero will result in exception ... enter a value other than 0 for 'b'

No comments:

Post a Comment