📘 Lesson · Lesson 31
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
throwto raise it andthrowsin 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 मेंthrowsuse करें।
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.