Python Error Handling
Python Error Handling
Python error handling involves managing exceptions that occur during program execution. Proper error handling ensures your program runs smoothly and fails gracefully when unexpected conditions occur.
Key Concepts in Python Error Handling
-
Exceptions: Runtime issues that interrupt the usual execution of a program:
ZeroDivisionErrorFileNotFoundErrorValueErrorTypeError
-
tryandexcept:- The
tryblock encloses code that could trigger an exception. - The
exceptblock intercepts and processes exceptions.
- The
-
else: Executes code if no exceptions occur in thetryblock. -
finally: Executes code regardless of whether an exception was raised or not. -
Raising Exceptions: You can explicitly raise exceptions using the
raisestatement. -
Custom Exceptions: You can define your own exceptions by creating a class derived from the
Exceptionclass. try: Protects the code that might cause an exception.except: Specifies how to handle specific exceptions.else: Block runs only when thetryblock executes without errors.finally: Ensures that clean-up code runs, like closing files or releasing resources.-
Be specific in exception handling to avoid masking unintended errors.
except (ValueError, TypeError): # Catch specific exceptions
- Avoid a generic
except:as it captures all exceptions, includingSystemExitandKeyboardInterrupt. -
Always clean up resources using
finallyor context managers.with open("example.txt", "r") as file: content = file.read()
Syntax and Examples
1. Basic try and except
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter a number.")
2. Using else
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
else:
print(f"Result: {result}")
3. Using finally
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Error: File not found.")
finally:
print("Execution completed, cleaning up...")
4. Raising Exceptions
def check_positive(number):
if number < 0:
raise ValueError("The number must be positive.")
return number
try:
print(check_positive(-5))
except ValueError as e:
print(f"Error: {e}")
5. Creating Custom Exceptions
class CustomError(Exception):
pass
def check_condition(value):
if value != "expected":
raise CustomError("Unexpected value provided!")
try:
check_condition("unexpected")
except CustomError as e:
print(f"Caught a custom exception: {e}")
Explanation of Each Block
Best Practices
By mastering error handling, you can make your Python programs more robust and user-friendly!
Prefer Learning by Watching?
Watch these YouTube tutorials to understand Python Tutorial visually:
What You'll Learn:
- 📌 Learn Python EXCEPTION HANDLING in 5 minutes!
- 📌 Python Exception Handling Tutorial for Beginners