Exception Handling in JAVA 8
User defined Exception
You can also create your own exception subclass 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.
Example:
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 span="" style="color: #7f0055; font-weight: bold;">throw0>
new MyException(a); }
else {
System.out.println(a+b); } }
public static void main(
String[] args) {
try { sum(-10, 10); }
catch(MyException me) {
System.out.println(me); } } } Output : MyException[-10] is less than zero
Points to Remember:
1. Extend the Exception class to create your own ecxeption class.
2. You don't have to implement anything inside it, no methods are required.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.
Dinesh Kumar S is a 23-year-old System Administrator who enjoys playing games, listening to music and learning new technology. He is friendly and generous, but can also be very lazy and crazy.
Share this
Learn-JAVA