User defined Exception subclass
You can also create your own exception sub class simply by extending java Exception class. You can define a constructor for your Exception sub class (not compulsory) and you can override the toString() function to display your customized message on catch.
class MyException extends Exception
{
private int ex;
MyException(int a)
{
ex=a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}
class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception class
}
else
{
System.out.println(a+b);
}
}
public static void main(String[] args)
{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); //it calls the toString() method of user-defined Exception
}
}
}
MyException[-10] is less than zero
Points to Remember
- Extend the Exception class to create your own exception class.
- You don't have to implement anything inside it, no methods are required.
- You can have a Constructor if you want.
- You can override the toString() function, to display customized message.
0 comments:
Post a Comment