throw and throws keyword-interview
Q1. What happens if an exception is thrown but not declared with throws?
- For checked exceptions → Compilation error.
- For unchecked exceptions → Compiles and runs, since they don’t require explicit declaration.
Q2. Can we throw an exception from finally block?
Yes, but it is not recommended. If both try and finally throw exceptions, the one from finally will override the try exception.
Q3. Is it mandatory to declare unchecked exceptions with throws?
No. throws is optional for unchecked exceptions (RuntimeException and its subclasses).
Q4. Can we throw an error using throw?
Yes. Both Exceptions and Errors (since both extend Throwable) can be thrown using throw.
Q5. What is the key rule of throw regarding object creation?
The object after throw must be an instance of Throwable or its subclasses (Exception, Error, etc.).