Exception Handling in Python
Python tutorial · PySpark.in
Introduction
When a program encounters an error, it usually stops execution and shows an error message. These errors are called exceptions. Python provides a way to handle exceptions gracefully using exception handling, which helps your program continue running even if an error occurs. An exception is an event that occurs during the execution of a program that disrupts the normal flow.
Example of an Exception
```
print(10 / 0) # This will raise a ZeroDivisionError
```
Why Exception Handling is Important
- Prevents the program from crashing.
- Helps provide meaningful error messages to users.
- Makes debugging easier.
- Allows writing more robust and fault-tolerant programs.
Basic Exception Handling
Python uses try and except blocks to handle exceptions:
```
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a number.")
```
Explaination
- try: Code that may cause an exception is placed inside the try block.
- except: Code inside the except block runs if an exception occurs.
- Multiple except blocks can handle different types of exceptions.
Common Python Exceptions
Exception Type | Description | Example |
|---|---|---|
ZeroDivisionError | Division by zero | 10 / 0 |
ValueError | Invalid value | int("abc") |
TypeError | Operation on incompatible types | "5" + 5 |
IndexError | Index out of range | arr[5] |
KeyError | Dictionary key not found | dict["age"] |
FileNotFoundError | File does not exist | open("data.txt") |
The else and finally Blocks
- else: Runs if no exception occurs.
- finally: Runs always, whether an exception occurs or not.
```
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful, result:", result)
finally:
print("Program execution finished.")
```
Handling Multiple Exceptions Together
You can catch multiple exceptions in one line:
```
try:
x = int(input("Enter a number: "))
print(10 / x)
except (ZeroDivisionError, ValueError) as e:
print("An error occurred:", e)
```
Nested Try-Except
You can nest try-except blocks for more control:
```
try:
num = int(input("Enter a number: "))
try:
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
```
Example: File Handling
Exception handling is very useful when working with files:
```
try:
file = open("data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
print("Closing the file...")
try:
file.close()
except NameError:
print("File was not opened.")
```
Raising Exceptions
You can manually raise exceptions using the raise keyword:
```
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("Sorry, you must be at least 18 years old.")
```
Effective Exception Handling
- Catch specific exceptions, not all (except Exception is a last resort).
- Always use finally to release resources like files,database or network connections.
- Provide helpful error messages for users.
- Use raise for custom validation rules in your programs.
- Handle only specific exceptions, not all errors.
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges