Checked and unchecked exceptions
Java's Throwable hierarchy (Error, Exception, RuntimeException), the catch-or-declare rule, the throws clause and the choice of type when you write your own exception.
- 26 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Checked exception: what is it?
Show the answer
An exception the compiler forces you to deal with: any call that can throw it must be wrapped in a compatible catch or declare it in the signature.
It is any subclass of
Exceptionthat is not aRuntimeException:IOException,SQLException,InterruptedException. Without handling, javac rejects the code.javac rejects this code with
unreported exception FileNotFoundException; must be caught or declared to be thrown. Which fix is valid, without changing the signature ofopen?
```java
static void open() {
new FileReader("a.txt");
}`- Wrap the call in a
trywithcatch (FileNotFoundException e) - Write
throwin front ofnew FileReader("a.txt") - Wrap the call in a
trywithcatch (RuntimeException e) - Declare
throws IOExceptiononmain, which callsopen
Show the answer
Wrap the call in a
trywithcatch (FileNotFoundException e)The
catchmust targetFileNotFoundExceptionor one of its checked parents (IOException,Exception).RuntimeExceptionis not one of them, andthrowraises an exception instead of handling one.- Wrap the call in a
RuntimeExceptionand its subclasses are …; the other subclasses ofException, likeIOException, are ….Show the answer
RuntimeExceptionand its subclasses are unchecked; the other subclasses ofException, likeIOException, are checked.The line runs through
RuntimeException: it, and notException, marks the exceptions the compiler does not check.Unchecked exception: what is it?
Show the answer
An exception whose handling the compiler does not impose:
RuntimeExceptionand its subclasses, as well asErrorand its own.NullPointerException,ArithmeticExceptionorIllegalArgumentExceptioncan show up almost anywhere: handling them at every call would drown the code. You fix the bug instead.A method loads a configuration file. If it is missing, the caller can offer another path. Which type of exception should you write for this case?
- A class extending
Error, since the file lies outside of the program itself - An unchecked exception, because in practice no caller will write a
tryblock for it - A checked exception extending
Exception: the caller can react and the compiler makes it do so - A
RuntimeException, because files are only read at the moment the program runs
Show the answer
A checked exception extending
Exception: the caller can react and the compiler makes it do soChoose checked when the caller can reasonably recover. For a caller's bug (a negative argument, a null reference), throw an unchecked exception such as
IllegalArgumentExceptioninstead.Erroris reserved for the virtual machine.- A class extending