An exception is an error that a program encounters when it is running. While some errors cannot be dealt with directly by the program, many of these exceptions can be caught and handled directly in our programs.
Exceptions in Flowcharts & Pseudocode
There isn’t really a standard way to display exceptions in flowcharts and pseudocode, but we can easily create a system that works well for our needs. Below are the flowchart blocks and pseudocode examples we’ll use in this course to represent exceptions and exception handling:
Exceptions in Java
Let’s review the syntax for working with exceptions in Java.
In Java, we can use a Try-Catch statement to detect and handle exceptions in our code:
In this example, the program will try to open a file using the first command-line argument as a file name. There are several exceptions that could occur in this code, such as an
IOException, and more. They can also be handled individually:
If desired, we can also throw our own exceptions in Java:
This will cause an exception to be thrown if the value of
y is equal to $0.0$.
We can also add a Finally block at the end of each Try-Catch block. This code will be executed whenever the control exits the Try-Catch block, even through the use of a
return statement to return from a method.
Try with Resources
When working with resources such as files in Java, we can also use a Try with Resources block to ensure that those resources are properly closed when we are done with them. In addition, a Try with Resources block will automatically catch and suppress any exceptions that result from trying to close the resource after an exception has occurred, preventing us from being bombarded by unavoidable exceptions. Here’s an example:
In this example, we are opening a
Scanner object within parentheses after a
try keyword. That
Scanner will automatically be closed once the program leaves the Try with Resources block where it is declared.