No matter how well crafted your code, you will inevitably come across an error every once in a while. Unfortunately, Python’s default setting when catching an error is to crash the program.
In the example below, I accidentally asked for a letter, when the code int(input()) is looking for an integer.
So when I enter a string, I get an error
Using Try, we can handle such mishaps in a more elegant fashion
The syntax is a follows:
try: Your Code except: What to do if your code errors out else: What to do if your code is successful
And as you can see from above, it doesn’t just protect against code errors, but it protects against user errors as well.
Using a while loop, we can give the user another chance if they don’t enter a number the first time.
- while True: – starts an infinite loop
- continue – returns to the beginning of the while loop
- break – exits the loop
You can add the finally: command to the end of a try: statement if you have something you want to execute regardless of whether there was an error or not.
You can also determine what your program does based on the type of error
A list of Exception types can be found here: Link
If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT.
Last Lesson: Enumerate() and Sort()
Next Lesson: Lambda, map, reduce, filter
Back to Python Course: Course