Tuesday, 29 November 2016

Program to throw user defined exception if the given number is not positive

The given program contains an exception class MyException which throws negative and positive number exception. We have to read a number from user at run time and throw an exception if the the entered number is negative or positive. Here we have used the BufferedReader class to read data from keyboard. The readLine( ) method is used to read a string from keyboard and parseInt( ) method converts String object into integer number. parseInt( ) is the method of Integer wrapper class.

PROGRAM
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class MyException extends Exception
{
 public MyException(String str)
 {
  System.out.println(str);
 }
}

public class SignException {

 public static void main(String[] args)throws IOException {
  
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Input number :: ");
  
  try {
   int num = Integer.parseInt(br.readLine());
   if(num < 0)
    throw new MyException("Number is negative");
   else
    throw new MyException("Number is positive");
  }
  catch (MyException m) {
   System.out.println(m);
  }
 }

}
OUTPUT 1
C:\>javac SignException.java
C:\>java SignException
Input number :: 45
Number is positive
exception.MyException
OUTPUT 2
C:\>javac SignException.java
C:\>java SignException
Input number :: -35
Number is negative
exception.MyException

No comments:

Post a Comment