Handling Exceptions Flashcards
(26 cards)
Exceptions represent errors that occur while…
…code is executing
Java signals an error with…
…an Exception object
The Exception object includes…
…a human readable message and a stack track showing the method calls that led to the error.
Java signals an error with an Exception. Then…
…the Exception is passed up the call stack until it’s handled.
What happens if an Exception is not handled?
The program will stop running. This is why it is important to handle exceptions when possible.
Two types of exceptions:
- checked
- unchecked
- a checked exception is verified by the compiler
- an unchecked exception == a run-time exception, is not verified by the compiler
Facts about a checked exception:
- a checked exception is verified by the compiler
- a checked exception is declared in code as part of a method’s signature
- a checked exception must be handled, either in the method, or by the code calling the method (enforced by the compiler)
What does “handling” an exception mean?
the exception is caught and resolved or acted upon
what are some ways to handle an exception?
- print or log an error message
- recovering (means catch and continue, e.g can log then continue?)
- throwing a new type of Exception
- polite message to the user to try again
- automatically retry
- user-friendly error message and fail
- user friendly error message and continue
Adding the exception to the method signature is known as propagating the exception
Propagating the exception signals the exception should be passed up the chain to the code that called the method
public void write(String str) throws IOException
–when we write code that calls this method…
… we must either handle the exception (try/catch) or propagate it (put in our signature or catch it and throw new exception)
Facts about unchecked exceptions:
- the Java compiler cannot predict an unchecked e
- typically a bug and is an unrecoverable error
- subclass of RuntimeException
- may be thrown without being declared or handled
- compiler does require these to be handled at compile time
Some examples of unchecked exceptions
- NullPointerException (access an object that hasn’t been created yet)
- calculation amounts to zero in the denominator (ArithmeticException)
- Integer.parse(“not a number”) –> NumberFormatException
- NumberFormatException is a type of IllegalArgumentException (which is a type of Runtime Exception)
Some notes about try/catch blocks
- tells the compiler that there may be exceptions thrown within the code inside the try block
- we can choose to 1) put most of a method within the block 2) just the line that may throw an exception 3) create multiple catch blocks for that try 4) create multiple try/catch blocks within the method
It all depends on how we want the code to proceed when an exception occurs
a catch block…
catch (Exception e) {
..
}
…defines the type of exception being caught, a variable name for that exception to use within the catch block, and code within the block to execute when such an exception occurs in the preceding try block.
One or more catch blocks can be defined after each try block.
An exception is thrown.
The runtime will look for a catch block…
..matching that type of exception being thrown–> this includes any exception type in an exception’s inheritance chain - THE SUBCLASSES of an exception, not any superclass
…the runtime will only execute the first matching catch block by passing in the exception object
…if not matching catchblock is found, the exception is passed up to the caller of the method that is executing (the next method on the call stack)
…Once the catch block executes, the runtime continues after the try and catch blocks (unless the catch block throws a new error?)
How to print the exception user readable error message?
catch (Exception e)
System.out.println(e.getMessage());
in the following code: try { Order ord=orderDataAccess.get(orderId); return fulfullmentService.process(ord) } catch (SQLException e) { System.out.println(..... } return false;
why are two lines of code in the try block?
because if the orderDataAccess returns a SQLException, we don’t want the fulfillment to be processed.
If it was after the try/catch block, Java would continue with this line after the error is caught.
We do not want to fulfill an order if we are unable to retrieve one from the OrderDataAccess.
(two lines are coupled functionally)
try { Order ord=orderDataAccess.get(orderId); return fulfullmentService.process(ord) } catch (SQLException e) { System.out.println(..... } catch (NoFulfillerFoundException e) { .... } return false;
Here, the exceptions are handled/logged, and the boolean false is sent back to the calling method. The exceptions are not propagated here.
is it a good idea to catch the generic Exception at the end of a try/catch block?
No, because we might squash the indication of serious erros that should bubble up, or that should stop the program. It could hide issues like: - permission problems - file system access - memory problems
Write exceptions to handle specific problems, limit catch blocks to exception types we plan to recover from.
Syntax differences between propagating checked and unchecked exceptions
checked exception
- add the checked exception to my own method’s signature
- catch the checked exception and throw a different exception - this different exception must be declared in my own method’s signature IF it is a checked exception
uncheckedexception
- it is automatically propagated
- catch the unchecked exception and throw a different one - this different exception must be declared in my own method’s signature IF it is a checked exception
If an exception is propagated …
…execution in that method is done.
If we create a subclass of a class that has methods declaring exceptions... (same for using an interface)
...we can't make the declarations (of the thrown exception) more generic ...the subclass cannot throw new checked exceptions ...subclasses may leave off declared exceptions (may avoid situations where checked exceptions occur)
If an exception is something we can recover from in my method…
my method should handle it. Leave the program in a state that allows execution to continue.