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:
ZeroDivisionError
FileNotFoundError
ValueError
TypeError
-
try
andexcept
:- The
try
block encloses code that could trigger an exception. - The
except
block intercepts and processes exceptions.
- The
-
else
: Executes code if no exceptions occur in thetry
block. -
finally
: Executes code regardless of whether an exception was raised or not. -
Raising Exceptions: You can explicitly raise exceptions using the
raise
statement. -
Custom Exceptions: You can define your own exceptions by creating a class derived from the
Exception
class. try
: Protects the code that might cause an exception.except
: Specifies how to handle specific exceptions.else
: Block runs only when thetry
block 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, includingSystemExit
andKeyboardInterrupt
. -
Always clean up resources using
finally
or 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!