What are Custom Exceptions in Java?
Custom Exceptions wahi hote hain jo aap apni specific application ki zaroorat ke hisab se banaate hain. Ye standard Java exceptions ki jagah ya unke alawa extra information dene ke liye use hote hain.
Creating Custom Exception Classes - Steps
- Custom exception class ko
Exception
(checked exception) yaRuntimeException
(unchecked exception) se extend karna hota hai. - Constructors create karne chahiye jisme message aur cause (Throwable) parameter include hon taaki exception ki origin trace ki ja sake.
- Extra fields aur methods bhi add kar sakte hain jisse exception specific information provide kare.
- Javadoc comments likhna behtar hota hai taaki API users ko samajh aaye.
Example: Custom Checked Exception Class
/**
* Exception thrown when an invalid age is provided.
*/
public class InvalidAgeException extends Exception {
private final int age;
public InvalidAgeException(String message, int age) {
super(message);
this.age = age;
}
public int getAge() {
return age;
}
}
Using the Custom Exception
Custom exception ko throw karne aur catch karne ka example:
public class Registration {
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above.", age);
}
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
System.out.println("Invalid age provided: " + e.getAge());
}
System.out.println("Program continues...");
}
}
Best Practices for Custom Exceptions
- Meaningful Names: Exception class ke naam me 'Exception' shabd ka istemal kare (jaise
InvalidAgeException
). - Useful Information: Extra info provide karne ke liye extra fields/methods add kare.
- Constructors: Standard constructors ka implementation kare jisme cause pass karna shamil ho.
- Document Well: JavaDoc comments ke saath clear documentation de.
- Avoid Generic Exceptions: Generic
Exception
class throw karne se bache, specific custom exceptions use kare.
When to Use Custom Exceptions?
Jab aapko kisi unique error state ko represent karna hota hai jise Java ke built-in exceptions se achhi tarah handle nahi kiya ja sakta tab custom exception bana ke use karna chahiye. Yeh code readability aur maintainability badhata hai.