Java Program to Implement User Defined Exception

User Defined Exception or custom exception is making your very own exception class and throws that exception by making use of 'throw' keyword. This should be possible by broadening the class Exception.

Java Program to Implement User Defined Exception
import java.util.Scanner;
class NegativeNumberException extends Exception
{
String description="Neagtive Number";
NegativeNumberException(String d)
{
description = d;
}
public String toString(){
    return ("Descrition = " + description);}
}
class UserException
{
public static void main(String[] args) {
try{
int a;
System.out.print("Enter a Positive Number : ");
        Scanner sc = new Scanner(System.in);
        a = sc.nextInt();
        if(a<0)
        {throw new NegativeNumberException("You have entered a Negative Number.");}
       }
      catch(NegativeNumberException exp){
       System.out.println(exp);
      }
}

}
OUTPUT :
Enter a Positive Number: -65
Description = You have entered a Negative Number.


tags : java , java programs , java code , java languages , java tutorials , java tutorialspoint , tutorialspoint , c , programs of c , c++ , programs of c++ , codecamp , learn java.

Post a Comment

Previous Post Next Post