In this tutorial, you will learn about exception handling in Python, focusing on how to use try-except blocks. Exception handling is crucial for writing sturdy, fault-tolerant code that can gracefully handle runtime errors.
You will learn:
- What exceptions are in Python
- How to use try-except blocks to handle exceptions
- The different types of exceptions
- How to handle multiple exceptions
Basic knowledge of Python is required. Familiarity with control flow (if-else statements, for loops, while loops) is beneficial.
An exception is an event that occurs during the execution of a program, disrupting the normal flow of the program's instructions. This event is typically due to an error.
A try-except block in Python is used to catch and handle exceptions. Python executes code following the try
keyword as a "normal" part of the program. If an exception occurs, the code under try
is skipped, and the code under except
is executed.
You can handle multiple exceptions by using multiple except
blocks. Each except
block handles a specific exception type.
try:
# this code is executed first
x = 5 / 0
except:
# this code is executed if there is an exception
print("An error occurred")
In this example, we try to divide by zero, which raises a ZeroDivisionError
. Since it's inside a try
block, the error is caught and the program prints "An error occurred" instead of crashing.
try:
# this code is executed first
x = 5 / 0
except ZeroDivisionError:
# this code is executed if there is a ZeroDivisionError
print("Tried to divide by zero")
Here, we specify the exception type in the except
keyword. This block will only catch ZeroDivisionError
exceptions.
In this tutorial, we learned about exceptions in Python and how to handle them using try-except blocks. We also covered how to handle multiple exceptions using multiple except blocks.
Write a program that asks the user for an integer and prints the square of it. Use a while loop with a try-except block to account for incorrect inputs.
Write a function that accepts two numbers and divides them. Use a try-except block to catch any potential exceptions.