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 Python
Let’s review the syntax for working with exceptions in Python.
In Python, we can use a Try-Except 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 a
FileNotFoundError, and more. They can also be handled individually:
If desired, we can also raise our own exceptions in Python:
This will cause an exception to be thrown if the value of
y is equal to $0.0$.
We can also add Else and Finally blocks at the end of each Try-Except block. A Finally block will be executed whenever the control exits the Try-Except block, even through the use of a
return statement to return from a method. The Else block will be executed if the entire Try-Except block completes without any exceptions being raised:
When working with resources such as files in Python, we can also use a With block to ensure that those resources are properly closed when we are done with them. In addition, a With 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 file using the
open() method inside of the With statement. That file will automatically be closed once the program leaves the With statement.