TNS
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
✓
Angular
0%
✓
Astro
0%
✓
Svelte
0%
✓
Vue.js
0%
✓
Other
0%
✓
I only use React
0%
✓
I don't use JavaScript
0%
Python / Software Testing

Python Try … Except: What It Is and How to Use It

Python on its own doesn't provide informative answers about what error is causing your application to stop. Try ... except fills in the gaps.
Sep 15th, 2024 5:05am by
Featued image for: Python Try … Except: What It Is and How to Use It
Featured image via Unsplash+.

The more complicated your code, the more you’ll depend on dealing with exceptions. If you’ve yet to run across exceptions, they are errors that occur during the execution of a program. With Python, exceptions don’t produce informative errors but, rather, will just stop. When your application stops without explanation, you (or your users) could be at a loss.

For Python, there’s a one-two punch to help ease this problem, try … except. Try allows you to test a block of code for errors and except allows for the handling of errors.

Think of it this way:

Python will try to execute your code and if an error occurs, except deals with it.

The structure of try … except looks like this:


Here’s a very simple example of try … except:


If you run the above, the output will be:


Why is this? In the above code, x was never defined. To better illustrate that, let’s run only the print(x) line, which will output:


When we have the try … except block, Python will see that x isn’t defined, then go to the except section and execute the second print line.

It’s also possible to specify the error to watch out for. Let’s stick with what we know (in this case, NameError). Take a look at the following code block:


You can probably predict what the output will be:


There are other types of exceptions that can be caught with try … except, such as:

  • Exception: Non-system-exiting exceptions and user-defined exceptions.
  • ArithmeticError: Various arithmetic errors.
  • BufferError: When a buffer-related operation cannot be performed.
  • LookupError: When a key or index on a mapping or sequence is invalid.
  • AssertionError: When an assert statement fails.
  • AttributeError: When an attribute reference or assignment fails.
  • EOFError: When a function hits an end-of-file condition without reading any data.
  • ImportError: When an import statement has trouble loading a module or when a “from list” has a name that cannot be found.

You’ll find a complete list of Python exceptions in the official documentation.

Remember the example above that had two except statements? You can also use a finally statement that will be executed regardless if a code block raises an error. The finally statement looks like this:


You might assume the above block of code will print out the single line:


However, the finally statement executes the code regardless, so the output will actually be:


The finally statement can be helpful for closing objects and cleaning up valuable resources.

Create a code block that will create a file for writing, write to the file, close the file and then print an error should something go wrong. The code block looks like this:


Can you guess what the output for the above will be? If you guessed Something went wrong when opening the file, you are correct. We received this error because the newstack.txt file wasn’t opened with write permissions.

Give the file proper access like this:


When you run the above code, no error will appear in the output. Instead, the line Hello, New Stack! is written to the newstack.txt file. No errors. However, thanks to the finally statement, you know the newstack.txt file was properly closed, so you’re good to go.

You can also raise an exception using the raise keyword. The raise keyword is used to raise exceptions and stop the flow of the program. For example, this can be used to stop a program if a user inputs data outside of the required parameters.

Here’s how the raise keyword works:


The output of the above command will include the statement:


Why? Because New Stack is a string and not an integer.

And that, my friends, is the gist of Python’s try … except statement. This will come in very handy to ensure your Python programs are better capable of handling errors that occur either from programming issues or user input.

Group Created with Sketch.
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.