Exception handling
In programming, things don't always go as planned. You might try to divide by zero, access a file that doesn’t exist, or reference a variable that hasn’t been defined. These unexpected events are called exceptions.
If not handled, exceptions can cause your program to crash. Fortunately, Python provides powerful tools to catch and handle exceptions, allowing your program to continue running even when errors occur.
What is an Exception?
An exception is an error that happens during the execution of a program. Common reasons for exceptions include:
- Dividing by zero: This raises a
.ZeroDivisionError
- Accessing invalid indexes: Attempting to access a non-existent index in a list raises an
.IndexError
- File issues: Trying to open a file that doesn’t exist raises a
.FileNotFoundError
When an exception occurs, Python stops running the program unless the error is handled.
Handling Exceptions: The try
and except
blocks
To handle exceptions, Python uses the try
except
The try
block
try
The try
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: You can't divide by zero!")
In this example, dividing by zero raises a ZeroDivisionError
except
block and prints an error message.
The except
block
except
The except
- Handle specific exceptions.
- Use a generic
block to catch any error.except
Example: Handling multiple exceptions
try:
x = int(input("Enter a number: "))
result = 10 / x
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter a valid number.")
Here:
- A
occurs if the user enters 0.ZeroDivisionError
- A
occurs if the user enters a non-numeric value.ValueError
Additional Exception handling blocks
The else
block
else
The else
try
block. It’s great for code that should execute when everything works as expected.
try:
x = int(input("Enter a number: "))
result = 10 / x
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input.")
else:
print(f"The result is: {result}")
The finally
block
finally
The finally
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
print("Cleaning up...")
if 'file' in locals() and not file.closed:
file.close()
Even if the file doesn’t exist, the finally
Catching all Exceptions
If you’re unsure what kind of error might occur, you can use a generic except
try:
x = int(input("Enter a number: "))
result = 10 / x
except Exception as e:
print(f"An error occurred: {e}")
The variable e
Raising Exceptions manually
Sometimes, you might want to intentionally raise an exception. Use the raise
def check_age(age):
if age < 18:
raise ValueError("You must be at least 18 years old!")
print("Access granted.")
try:
check_age(16)
except ValueError as e:
print(e)
In this example, a ValueError
Why use Exception handling?
- Avoid crashes: Handle errors gracefully to keep your program running.
- Improve user Experience: Provide meaningful messages instead of cryptic error codes.
- Cleaner code: Separate normal operations from error-handling logic, making your code easier to read and maintain.
Conclusion
Exception handling is a vital skill for writing robust and reliable Python programs. By mastering try
except
else
finally
As you practice, you’ll be able to write programs that are not only functional but also resilient to unexpected issues.