Chapter 15 - Exception Handling Flashcards
What can some API methods lead to because they are dangerous?
A runtime error
What is a technique for handling runtime errors?
Use exception handling. More specifically, surround the method call with a try block and insert a catch block immediately after the try block.
Try/Catch sytax and code example
What does NumberFormatException tell a user?
It’s thrown when a number’s format is inappropriate.
What causes the NumberFormatException to be thrown?
It’s thrown my one of the parse methods (Integer.parseInt, Long.parseLong, Double.parseDouble etc.)
When there’s an attempt to convert a string to a number and the string’s character don’t form a valid number.
How large can try blocks be?
Big or small, depends on the need.
It is legal to surround an entire method body with a try block, but that’s usually counterproductive because it makes it harder to identify the “dangerous” code.
What should you do if you have a chunk of code that has several “dangerous” method/constructor calls?
- Add a seperate try-catch structure for each scuh call might result in cluttered code
- To prevent this and improve program readability, consider using a single try block that surrounds the calls.
What does the JVM do if an exception is thrown?
It immediately jumps out of the current try block and looks for a matching catch block. The immediacy of the jump means that if there are statements in the try block after the exception-throwing statement, those statements are skipped.
What does the compiler assume in regards to a try block?
It knows that statements inside a try block might be skipped, so in turn it assumes that all statements inside a try block get skipped.
What can happen if an assignments is within a try block, but the same assignment doesn’t exist outside of the try block?
It can give you the following compilation error:
variable x might not have been initialized
How do you fix the variable x might not have been initialized error?
Initialize the variable prior to the try block.
What are the two types of exceptions?
Checked and Unchecked.
What is a check exception?
Checked exceptions are required to be checked with a try-catch mechanism.
What is an unchecked exception?
Unchecked exceptions are not required to be checked with a try-catch mechanism (but, as an option, unchecked exceptions may be checked with a try-catch mechanism)
How can you tell if a particular exception is classified as checked or unchecked?
- Look up its associated class in the API documentation
- On the class’s API page, look at its class hierarchy tree. If you find that the class is derived from the RuntimeException class or from the Error exceptions class, then it’s an unchecked exception. Otherwise, it’s a check exception.