We have just learned about functions. In this lab we learn about 'exception handling', e.g. How to handle errors properly.
1. Ensure that you are signed into GitHub
Open the assignment: Project 4 - Dice Roller
Open lab3.py
The try/except block in Python is used to catch and handle exceptions.
An exception in programming is like a hiccup that stops your code from running smoothly. It's a problem that pops up, which your program isn't sure how to handle. For example, if your code tries to divide a number by zero, it can't do that, so it throws an exception, saying, "I can't do this." If you don't have a way to handle this hiccup, your program will just stop and give an error message. But if you plan for it, you can tell your program what to do next, like asking for a different number instead of zero.
try is the block where you place the code that might raise an exception.
except is the block where you handle the exception that was raised in the try block.
Run the program below and enter 0. You can't divide by zero so the program throws a 'ZeroDivisionError'.
We now run the exact same program inside a try block. If you enter 0 the except block catches this and prints a friendly error message.
We now expand the same program again but with a while loop. If the try block is successful we break out of the loop.
If there is an exception we print a friendly error message and loop around to try again. This is a great way to do input validation.
We saw above that this is useful for handling division by zero; however there are many more scenarios where you will want to use exception handling.
Handling Invalid Input
This program expects a valid integer input. If the user enters a non-integer value, a ValueError is raised, and the except block handles it.
Handling File Operations
This tries to open a file that doesn’t exist, raising a FileNotFoundError. The except block catches this and informs the user.
Accessing a List Out of Range
When trying to access an index in a list that does not exist, Python raises an IndexError. You can catch this with an except block:
Key Error in Dictionaries
Trying to access a dictionary with a key that does not exist will raise a KeyError:
You might have noticed an extra word after except in some of the examples above. This the name of the exception that the block is meant to handle.
This is optional, but helps with debugging and informing the user of what went wrong. Here is an example where we can catch different errors:
Try entering:
0 - to cause a division by zero
abc - to cause a value error
3 - to access an index of the list that doesn't exist
2 - to see the program actually work!
Complete the following requirements:
Define a function called get_number(prompt) that returns an integer.
Include a while loop and try/except blocks inside the function to handle non-integer inputs.
Use the get_number function to ask for a numerator, then again for a denominator.
Divide the numerator by the denominator and print the result, handling any division by zero errors.
Use the get_number function to ask the user for an index to access an element from a predefined list.
Print out the value from the list, handling the index error if the user selects a non-existent index.
Press Ctrl + F5 to run the program or open a terminal and type python lab3.py
You should now know how to create and use functions with input validation and handle common errors in Python using try/except blocks.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 3 complete"
Press Commit to main
Press Push origin