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

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative