JAVA PROGRAM TO THROW NEGATIVE NUMBER EXCEPTION

/* java program to throw the negative number exception using Exception class... In this program ,take value from user,if user put negative number throw user defined exception */

PROGRAM CODE--

import java.util.Scanner;

import java.io.*;

class Number

{

    int m ;                                                         //class variable

  public void get(int no) throws Exception

{

     m=no;

    if(m<0)

{

    throw new Exception ("please enter only positive number");

}

else

{

   System.out.println(m);

}

}

}



class CheckNumber


{

    int n;

    public static void main(String a[])

{

     Scanner o = new Scanner(System.in);

     System.out.println("enter a number");

try

{

      int n = o.nextInt();

      Number ob = new Number();

     

   ob.get(n);

}catch(Exception e)

{

    System.out.println(e);

}


 OUTPUT OF ABOVE PROGRAM-----


Comments