IOException
, NullPointerException
, etc., and how to handle them using throw
and throws
.
Exception
class (for checked exceptions) or the RuntimeException
class (for unchecked exceptions).
Exception
(for checked exceptions) or RuntimeException
(for unchecked exceptions).
throw
keyword to throw the exception object in your code when the specific condition occurs.
try-catch
or propagate it using throws
.
// Step 1: Create a user-defined exception
class InsufficientBalanceException extends Exception
{
// Constructor with custom message
public InsufficientBalanceException(String message)
{
super(message);
}
}
// Step 2: Use the custom exception in application
class BankAccount
{
private double balance;
public BankAccount(double balance)
{
this.balance = balance;
}
// Withdraw method which may throw the user-defined exception
public void withdraw(double amount) throws InsufficientBalanceException
{
if(amount > balance)
{
throw new InsufficientBalanceException("Withdrawal failed: Insufficient balance!");
}
else
{
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}
}
}
public class MainApp
{
public static void main(String[] args)
{
BankAccount account = new BankAccount(5000);
try
{
account.withdraw(6000); // Trying to withdraw more than balance
}
catch (InsufficientBalanceException e)
{
System.out.println("Exception caught: " + e.getMessage());
}
try
{
account.withdraw(3000); // Valid withdrawal
}
catch (InsufficientBalanceException e)
{
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Exception caught: Withdrawal failed: Insufficient balance! Withdrawal successful. Remaining balance: 2000.0
InsufficientBalanceException
is our user-defined exception.
Exception
class, so it is a checked exception.
withdraw()
method, we throw this exception if the withdrawal amount exceeds the balance.
main()
, we handle it using try-catch
.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.