Error & Exception Handling in Python
Error and exception handling in Python is crucial for creating
robust and reliable programs. It allows you to gracefully handle
unexpected situations, such as user input errors or issues with file
operations, without crashing the program.
Types of Errors
1. Syntax Errors: These occur when the Python parser detects
incorrect syntax. They are also called parsing errors.
print("Hello world) # Missing closing quotation mark
2. Runtime Errors (Exceptions): These occur during the
execution of the program. They include a wide range of error
types such as ZeroDivisionError, FileNotFoundError,
TypeError, etc.
Handling Exceptions
Python provides a way to handle exceptions using the try, except,
else, and finally blocks.
1. try and except: The try block contains code that might
throw an exception, and the except block contains code to
handle the exception.
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Handling the exception
print("Cannot divide by zero!")
2. else: The else block is executed if no exception is raised in
the try block.
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)
3. finally: The finally block is executed no matter what,
whether an exception is raised or not. It is typically used for
cleanup actions, such as closing a file.
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
Catching Multiple Exceptions
You can catch multiple exceptions using multiple except blocks or
a single except block with a tuple of exceptions.
Multiple except blocks:
try:
# Code that may raise different types of exceptions
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
Single except block with a tuple:
try:
num = int(input("Enter a number: "))
result = 10 / num
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
Raising Exceptions
You can raise exceptions using the raise statement. This is useful
for generating custom exceptions.
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return age
try:
check_age(-1)
except ValueError as e:
print(e)