Exception Handling
Errors and exceptions are common in programming. Python provides a robust way to handle them so your program doesn't crash unexpectedly. Instead of breaking, you can manage errors and continue running the program smoothly.
What are Errors and Exceptions?
- Error: An issue in the code that prevents the program from running. For example:
- Syntax Errors (e.g., missing a colon : or parenthesis).
- Indentation Errors (e.g., improper spacing).
- Exception: An error that occurs during the execution of a program. Examples:
- Division by zero.
- Accessing a variable that doesn't exist.
Example:
# This will raise a ZeroDivisionError num = 10 / 0
Handling Exceptions with try and except
Python uses try and except blocks to handle exceptions. If an error occurs in the try block, the except block runs instead of crashing the program.
Basic Syntax:
try: # Code that may raise an exception risky_code() except ExceptionType: # Code to handle the exception handle_error()
Example:
try: num = 10 / 0 # This will raise a ZeroDivisionError except ZeroDivisionError: print("Cannot divide by zero!")
Multiple except Blocks
You can handle different types of exceptions with multiple except blocks.
Example:
try: num = int("hello") # This will raise a ValueError except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Invalid input!")
Catching All Exceptions
You can use except without specifying an exception type to catch any error.
Example:
try: result = 10 / 0 except: print("An error occurred!")
Using else with try
The else block runs if there is no exception in the try block.
Example:
try: num = 10 / 2 except ZeroDivisionError: print("Cannot divide by zero!") else: print("Division successful:", num)
The finally Block
The finally block always executes, whether there is an exception or not. Use it for cleanup tasks like closing files or releasing resources.
Example:
try: file = open("example.txt", "r") content = file.read() except FileNotFoundError: print("File not found!") finally: print("Closing the file...") if 'file' in locals() and not file.closed: file.close()
Raising Exceptions
You can raise exceptions intentionally using the raise keyword.
Example:
age = -5 if age < 0: raise ValueError("Age cannot be negative!")
Custom Exceptions
You can create your own exception classes by inheriting from the built-in Exception class.
Example:
class CustomError(Exception): pass try: raise CustomError("This is a custom error!") except CustomError as e: print(e)
Common Exceptions in Python
Exception | Description |
---|---|
ZeroDivisionError | Raised when dividing by zero. |
ValueError | Raised for invalid inputs. |
FileNotFoundError | Raised when a file doesn't exist. |
TypeError | Raised when an operation uses the wrong type. |
KeyError | Raised when a dictionary key is missing. |
IndexError | Raised when a list index is out of range. |
Example Program
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("You cannot divide by zero!") except ValueError: print("Invalid input! Please enter a number.") else: print("Division successful:", result) finally: print("Execution completed.")
Output 1:
Enter a number: 0
You cannot divide by zero!
Execution completed.
Output 2:
Enter a number: 5
Division successful: 2.0
Execution completed.