Java Core: Exceptions Flashcards
What are Exceptions in Java?
Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions.
What’s the difference between checked and unchecked exceptions?
i. Checked exceptions are exceptions expected to be handled in compile-time by either using a try-catch statement or using throws keyword.
ii. Unchecked exceptions extend Error or RuntimeException classes, which JVM can throw during runtime.
Explain the inheritance hierarchy of these exception classes - Exception, IOException, Throwable, Error, RuntimeException, NullPointerException.
- Error (unchecked) is –> Throwable.
- IOException (checked) is –> Exception (checked - is not RuntimeException) is –> Throwable. - NullPointerException (unchecked) is –> RuntimeException (unchecked) is –> Exception (checked - is runtime exception) is –> Throwable.
When are Errors thrown? How should you handle them?
The ‘Error’ should be left unhandled since there is no way to recover from an Error.
Should you catch ‘Throwable’?
The Throwable includes and Error that should be left unhandled (it indicates an unrecoverable program and stops the execution flow).
Can you use a ‘try-finally’ construct without using the ‘catch’ block?
Yes, the ‘finally’ block is meant for code that has to be executed regardless of errors thrown or caught in try ‘block’, for example, closing a file or connection.
When implementing your own custom exceptions, would you prefer checked or unchecked exceptions? Why?
(Unchecked) Usually, when designing your own exceptions, those are extensions of RuntimeExceptions, used to identify and pass along information on what exactly went wrong in the program’s logic - for example, missing mandatory information from an input, instead of a NullPointerException that has a broader meaning.