Lesson Contents
When an error occurs in your code, Python stops executing your code and generates an error message. In Python, an error is called an exception.
Here is a quick example to demonstrate this:
print(my_variable)
print("Testing exceptions")
Will show this output:
Traceback (most recent call last):
File "main.py", line 1, in
print(my_variable)
NameError: name 'my_variable' is not defined
The variable doesn’t exist, so Python throws a NameError exception. Our program stops so it never prints the “Testing exceptions” message. Here is one more example:
"This is the HTTP status code: " + 404
Will show this output:
Traceback (most recent call last):
File "main.py", line 1, in
"This is the HTTP status code: " + 404
TypeError: can only concatenate str (not "int") to str
Above, we see we get a TypeError exception because you can’t concatenate a string and an integer. Python has a list of built-in exceptions.
Try Except
The two examples above deal with exceptions in our own code. We could easily fix these, preventing those exceptions in the first place. This is not always possible though. For example, when you connect with an external network device through SSH or an API, it’s possible that the connection sometimes fails. We have to take this into account when we write our code.
We can use a try/except block. We add the code we want to run under the try block. When it fails, the except block handles the exception. Let me show you an example:
try:
print(my_variable)
except:
print("Variable does not exist")
Will show this output:
Variable does not exist
The variable we try to print doesn’t exist, so our code hits the except block.
Multiple Exceptions
In the example above we handled our exception but it was a “catch-all” except block. It’s also possible to deal with exceptions based on the exception error. Let me show you an example:
try:
print(my_variable)
except NameError:
print("Variable does not exist.")
except:
print("Another exception occurred.")
Will show this output:
Variable does not exist.
In the code above, we have an except block for NameError and the general except block. It hits our first except block because we ran into a NameError exception.
Else
If you want to do something when no exceptions are raised, you can add an additional else statement. Here is an example:
try:
print("Trying print")
except:
print("Variable does not exist.")
else:
print("Everything is OK.")
Will show this output:
Trying print
Everything is OK.
The try block didn’t run into exceptions and we executed the else statement. Here is one more example:
try:
print(my_variable)
except:
print("Variable does not exist.")
else:
print("Everything is OK.")
Will show this output:
Variable does not exist.
The code above will raise an exception because the variable I specify under the try block doesn’t exist. The else statement doesn’t run, because we hit the except block.
Finally
We can also run something in the end, independent from whether we hit the try or except block. We do this with the finally statement. Here is an example:
try:
print("Print something.")
except:
print("Variable does not exist.")
finally:
print("Printing this one way or another.")
Will show this output:
Print something.
Printing this one way or another.
In the example above, we hit the try block and we print something because of the finally statement. Here is one more example:
try:
print(my_variable)
except:
print("Variable does not exist.")
finally:
print("Printing this one way or another.")
Will show this output:
Variable does not exist.
Printing this one way or another.
This time we hit the except block but we still run whatever code we have after the finally statement.
Raise Exception
When you create your own programs, it’s also possible to generate your own exception error messages with the raise keyword. Here’s how:
connection_status = "FAIL"
if connection_status != "OK":
raise Exception("Connection failed.")
Will show this output:
Traceback (most recent call last):
File "main.py", line 4, in
raise Exception("Connection failed.")
Exception: Connection failed.
This raises a general exception with our message. It’s better to include the exact exception though. For example: