In: Computer Science
CREATE A NEW Java PROGRAM that demonstrates :
1.1 numeric and 1 string exception
2. Create your own user defined exception, COMMENT it well, and add code so that it is thrown.
Java Program:
//Exception Class
class UserException extends Exception{
String str1;
// Constructor
UserException(String val) {
//Storing message
str1=val;
}
//Method that prints the message
public String toString(){
return ("UserException Occurred: "
+ str1) ;
}
}
class ExceptionDemonstrater {
//Main method
public static void main(String[] args) {
//Number Exception
try
{
//Trying to
convert String to integer - Generates Exception
int n =
Integer.parseInt("One");
}
catch(NumberFormatException
ex)
{
//Handling and
printing exception message
System.out.println(ex.toString());
}
//String Exception
try
{
//Sample
String
String s =
"Hello World";
//Trying to
fetch a character from string with invalid index value - Generates
Exception
char ch =
s.charAt(100);
}
catch(StringIndexOutOfBoundsException ex)
{
//Handling and
printing exception message
System.out.println(ex.toString());
}
//User Defined Exceptions
try
{
//Throwing
Exception
throw new
UserException("User Defined Exception Generated.");
}
catch(UserException ex)
{
//Handling and
printing exception message
System.out.println(ex.toString());
}
}
}
_________________________________________________________________________________________
Sample Run: