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

Comments

  1. After a long time, I read a very beautiful and very important article that I enjoyed reading. I have found that this article has many important points, I sincerely thank the admin of this website for sharing it. Get for more information Quickbooks Customer Service Number

    ReplyDelete

Post a Comment

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.