Showing posts with label user defined exception handling. Show all posts
Showing posts with label user defined exception handling. Show all posts
Java user Defined Exception Handling - Hello Exception
/*
Write a java program for exception
handling:
To
create a user defined exception whenever user input the word "hello".
*/
// java Exception Handling
// user defined exception
import java.util.*;
class userdefinedexception extends
Exception
{
public
String toString()
{
return
("Hello Exception");
}
}
class UsrDefException
{
public
static void main(String args[])
{
String
str;
Scanner
s = new Scanner(System.in);
try
{
System.out.print("Enter
name : ");
str
= s.next().trim();
//
throw is used to create a new exception and throw it.
if(str.equalsIgnoreCase("HELLO"))
{
throw
new userdefinedexception();
}
else
System.out.print("Hello
"+str);
}
catch(userdefinedexception
e)
{
System.out.println(e)
;
}
}
}
/*
Sample output
D:\oopjava>javac UsrDefException.java
D:\oopjava>java UsrDefException
Enter name : asdf
Hello asdf
D:\oopjava>java UsrDefException
Enter name : hello
Hello Exception
D:\oopjava>
Java - exception Handling - user defined exception handling
// user defined exception
class userdefinedexception extends
Exception
{
int
a;
userdefinedexception(int
b)
{
a
= b;
}
public
String toString()
{
return
("Exception Number = "+a) ;
}
}
class JavaException
{
public
static void main(String args[])
{
try
{
//
throw is used to create a new exception and throw it.
throw
new userdefinedexception(2);
}
catch(userdefinedexception
e)
{
System.out.println(e)
;
}
}
}
Subscribe to:
Posts (Atom)