{ "metadata": {}, "nbformat": 4, "nbformat_minor": 5, "cells": [ { "id": "metadata", "cell_type": "markdown", "source": "
Try/except are a construct in Python used to catch a potential exception. Sometimes things go wrong in your code! Or in someone else’s code in a module. Sometimes some errors might be expected like when you try and read a user supplied file, maybe it isn’t available because they’ve specified the wrong path.
\n\n\nAgenda\nIn this tutorial, we will cover:
\n\n
\n- Raise
\n
When you’re writing code, sometimes there are errors you might need to handle:
\nlen(numbers)
and trigger a Zero Division Error.Using try/excepts allow you to:
\nFor instance, returning to the mean()
function example, what should mean([])
return for a hypothetical mean function that calculates the average of a list of numbers. Should it return 0? It probably should return an error. Let’s look at some example code:
This raises a ZeroDivisionError
but we can make this a more friendly error message by raising our own exception.
\n\n\nThere are loads of different types of exception codes! The python documentation has a large list of exceptions and some descriptions for when or why those exceptions might be raised.
\n
Now we get a much more useful error message from the function! Using raise
is especially important for library authors, people writing python modules that we all use. If they provide useful error messages, it helps you as an end user understand what’s happening.
Let’s look at how you would handle one of these exceptions, we’ll continue with the mean()
example above.
Here we use try:
to setup a new block, and this code is tried, Python attempts to execute it. Below are one or more except:
blocks which catch specific errors. Here we have specifically said we know a ValueError can happen, and decided to handle it.
Or for another example, accessing a user supplied file. Oftentimes users will call your program and supply a non-existent, or inacessible file. Here you can use multiple except
blocks to catch all of those potential errors.
Failing to open a file raises a FileNotFoundError
which indicates the file isn’t available, and PermissionError
indicates that a file is unreadable. However in practice, sometimes you’ll see something like this:
# Bad!\ntry:\n doSomething()\nexcept:\n print(\"error\")\n
This is called a bare exception, and will catch any exception, compared with except ValueError
which only catches value errors. People consider this generally a bad idea, termed code smell. (Because it smells (appears) bad!)
The last portion of the try:
/except:
block is finally:
, a third block which lets us do cleanup. It’s often very nice to your users that if your program fails halfway through, that you cleanup after yourself.
Sometimes we can use try
/except
to have a fallback option. Consider the pseudocode below:
try:\n runBlast()\nexcept BlastNotAvailable:\n try:\n runBLAT()\n except BLATnotAvailable:\n print(\"Neither Blast nor BLAT were available.\")\n
Sometimes you have a fallback option, some other tool you can use in its place. When that’s possible, you can use try
and except
to handle those cases and work around potential issues. But this isn’t always the case, sometimes you just need to print your error message and stop executing code.