Java - Custom Exception-interview
Q1. What is a custom exception in Java?
A custom exception (user-defined exception) is an exception class created by the programmer by extending Exception (checked) or RuntimeException (unchecked). It allows defining application-specific error handling.
Q2. When should we use a custom exception instead of built-in ones?
- When built-in exceptions don’t represent the specific problem.
- To provide clearer context and domain-specific error messages.
Q3. Difference between checked and unchecked custom exceptions.
- Checked custom exception → Extend Exception, must be handled using try-catch or throws.
- Unchecked custom exception → Extend RuntimeException, not mandatory to handle.
Q4. What are best practices while creating custom exceptions?
- Always extend Exception or RuntimeException.
- Provide meaningful names (e.g., InvalidUserException).
- Provide constructor with message and optional cause.
- Avoid creating too many custom exceptions unless necessary.
Q5.Can we create a custom exception without extending Exception or RuntimeException?
No. All exceptions in Java must be part of the Exception hierarchy. If you don’t extend Exception or RuntimeException, your class won’t be treated as an exception and cannot be used with throw or catch.