Advertisement
//Java - Example of user-defined exception
class myException1 extends Exception
{
public String toString()
{
return "User-Defined Exception";
}
public static void main(String... ar)
{
myException1 ob= new myException1();
try
{
throw ob;
}
catch(myException1 e)
{
System.out.println("Exception handled - "+ e);
}
}
}
Exception handled - User-Defined Exception
//Java - Example of user-defined exception
import java.io.*;
class myException1 extends IOException
{
public String toString()
{
return "User-Defined Exception by extending IOException";
}
public static void main(String... ar)
{
myException1 ob= new myException1();
try
{
throw new myException1();
}
catch(myException1 e)
{
System.out.println("Exception handled - "+ e);
}
}
}
Exception handled - User-Defined Exception by extending IOException
Advertisement
//Java - Example of user-defined exception
class myException2 extends Exception
{
int acc_bal=0; //current account balance
public String toString()
{
return "Cannot debit. Low Account Balance.";
}
public static void main(String... ar)
{
myException2 ob= new myException2();
try
{
ob.withdraw(100);
}
catch(myException2 e)
{
System.out.println("Exception handled - "+ e);
}
}
public void withdraw(int debitMoney) throws myException2
{
if(acc_bal>1000) //if account balance is greater than 1000$ then you can dedit money
{
acc_bal = acc_bal - debitMoney;
}
else // if account balance is less than 1000$ then debiting throws our user defined exception.
throw new myException2();
}
}
Exception handled - Cannot debit. Low Account Balance.
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement