Interview question
How do you create and throw a custom exception in Java? Java में custom exception कैसे बनाएं और throw करें?
Answer
Custom exceptions are created by extending Exception (for checked) or RuntimeException (for unchecked), letting you represent domain-specific error conditions clearly.
// Custom CHECKED exception - must be declared or caught
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double balance) { this.balance = balance; }
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(
'Cannot withdraw ' + amount + ', balance is only ' + balance);
}
balance -= amount;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(100);
try {
account.withdraw(150);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
}
}
// Custom UNCHECKED exception - no 'throws' declaration required
class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
public void setAge(int age) {
if (age < 0) {
throw new InvalidAgeException('Age cannot be negative: ' + age);
}
}
// Adding custom fields to an exception
class InsufficientFundsException2 extends Exception {
private final double shortfall;
public InsufficientFundsException2(double shortfall) {
super('Short by ' + shortfall);
this.shortfall = shortfall;
}
public double getShortfall() { return shortfall; }
}Custom exceptions Exception (checked के लिए) या RuntimeException (unchecked के लिए) को extend करके बनाई जाती हैं, domain-specific error conditions clearly represent करने के लिए।
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double balance) { this.balance = balance; }
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(
'Cannot withdraw ' + amount + ', balance is only ' + balance);
}
balance -= amount;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(100);
try {
account.withdraw(150);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
}
}
// Custom unchecked exception
class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
public void setAge(int age) {
if (age < 0) {
throw new InvalidAgeException('Age negative नहीं हो सकती: ' + age);
}
}Was this answer clear?