This is a Java Program to Handle the User Defined Exception Using Throw Keyword.A part from existing Exceptions in java, we can create our own Exceptions (User defined exceptions in java)
Here is the source code of the Java Program to Handle the User Defined Exception Using Throw Keyword. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
public class User_Defined_Exception
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Amount:");
int a=s.nextInt();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
System.out.println("Amount Deposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
}
Output:
$ javac User_Defined_Exception.java $ java User_Defined_Exception Enter Amount:-5 Invalid Amount
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Practice Information Technology MCQs
- Check Programming Books
- Apply for Java Internship
- Practice BCA MCQs
- Apply for Computer Science Internship