What you've seen up to now are the most common ways of handling exceptions in Python. You'll see many try except blocks, and for the safety of your programs, you should also get familiar with writing many of them :)
How to Use Python Else and Finally
However, there's more you can do in exception handling, and this lesson will introduce you to two additional keywords that you can use to further define the control flow of your program:
elsefinally
Both of these keywords are optional, and you don't need to use them during your exception handling. However, they can add specific functionality that might be useful for you.
Python Else
The try except blocks in Python have an optional else statement. You can use it after any except statements you wrote. The code inside the else block will only execute if the code wrapped in your try statement doesn't raise an exception:
try:
pass # Try some code
except:
pass # Handle the exception(s)
else:
pass # Do something only if no exception has been raised
The try except block will work the same as in an example without the else statement. The code inside the else block, however, will only run when no exception is raised at all.
Python Finally
The second optional statement starts with the finally keyword. The finally statement can come after any except blocks and, if present, after the else clause. The keyword is called finally, after all :)
The code inside the finally block will always run, no matter what happened before:
try:
pass # Try some code
except:
pass # Handle the exception(s)
else:
pass # Do something only if no exception has been raised
finally:
pass # Do something whether an exception was raised or not
A common use case of the finally statement is closing files. When you do file operations, you don't want to accidentally leave a file object open. This could cause all sorts of unexpected side effects.
You can, therefore, think of the finally block as a clean-up procedure to your try except construct. No matter what happened before, it will execute and do tasks that are necessary whether the previous code succeeded or not.
You've read a lot about catching exceptions and how to handle them when they occur. In the next lesson, you'll learn how you can raise exceptions when you want to make sure that some event in your program definitely gets your attention.
Summary: Python Try Except Else
- The
elsekeyword runs when no exception occurred - The
finallykeyword will always run, whether an exception occurred or not - Both
elseandfinallyare added to the end of thetry exceptblock