📘 Lesson  ·  Lesson 31

Custom Exceptions

Custom Exceptions

Why Custom Exceptions?

Sometimes built-in exceptions are not enough. You can create your own by extending the Exception class to represent specific errors.

Example

class AgeException extends Exception {
    AgeException(String msg) { super(msg); }
}

class Test {
    static void check(int age) throws AgeException {
        if (age < 18) throw new AgeException("Age must be 18+");
        System.out.println("Allowed");
    }
    public static void main(String[] a) {
        try { check(15); }
        catch (AgeException e) { System.out.println(e.getMessage()); }
    }
}
Age must be 18+

Summary

  • Create a custom exception by extending Exception and calling super(msg).
  • Use throw to raise it and throws in the method signature.

Custom Exceptions क्यों?

कभी-कभी built-in exceptions काफी नहीं होते। आप Exception class को extend करके अपनी exception बना सकते हैं specific errors दिखाने को।

Example

class AgeException extends Exception {
    AgeException(String msg) { super(msg); }
}

class Test {
    static void check(int age) throws AgeException {
        if (age < 18) throw new AgeException("Age must be 18+");
        System.out.println("Allowed");
    }
    public static void main(String[] a) {
        try { check(15); }
        catch (AgeException e) { System.out.println(e.getMessage()); }
    }
}
Age must be 18+

सारांश

  • Exception extend करके और super(msg) call करके custom exception बनाएं।
  • Raise को throw और method signature में throws use करें।
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n