Day 9: Exception Handling in Python – Python4AI
On this page
Day 9: Exception Handling in Python
Topics to Cover:
- Try-Except Blocks
- Custom Exceptions
Introduction to Exception Handling
In programming, errors are inevitable. Python provides a robust mechanism to handle these errors through exception handling. This ensures that your program can gracefully handle unexpected situations without crashing.
Try-Except Blocks
The try block lets you test a block of code for errors. The except block lets you handle the error.
Syntax:
try:
# Code that might raise an exception
pass
except ExceptionType:
# Code to handle the exception
pass
Example: Handling Division by Zero:
try:
numerator = 10
denominator = 0
result = numerator / denominator
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
In this example, attempting to divide by zero raises a ZeroDivisionError, which is then handled in the except block.
Custom Exceptions
Python allows you to define your own exceptions by creating a new class that is derived from the built-in Exception class.
Creating a Custom Exception:
class InvalidInputError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
Using Custom Exceptions:
def get_positive_number():
number = int(input("Enter a positive number: "))
if number < 0:
raise InvalidInputError("Invalid input: Number must be positive.")
return number
try:
print(get_positive_number())
except InvalidInputError as e:
print(e)
In this scenario, if the user inputs a negative number, an InvalidInputError is raised with a custom error message.
Potential Problems to Solve
Problem 1: Handling Division by Zero
Task: Write a program that handles division by zero.
Solution:
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Error: Cannot divide by zero."
return result
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
print(divide_numbers(numerator, denominator))
Problem 2: Custom Exception for Invalid User Input
Task: Create a custom exception for invalid user input and raise it in an appropriate scenario.
Solution:
class InvalidInputError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def get_positive_number():
number = int(input("Enter a positive number: "))
if number < 0:
raise InvalidInputError("Invalid input: Number must be positive.")
return number
try:
print(get_positive_number())
except InvalidInputError as e:
print(e)
Conclusion
Exception handling is a crucial aspect of writing robust Python programs. By using try-except blocks and custom exceptions, you can handle errors gracefully and provide meaningful feedback to users, ensuring a smoother user experience.
Stay tuned for Day 10 of the python4ai 30-day series, where we’ll dive into more advanced topics and continue building our Python expertise!
More in PythonForAI
See all →- Day 14: Matplotlib for Data Visualization Topics to Cover: Introduction to Matplotlib Basic Plotting Introduction to Matplotlib Matplotlib is a popular plotting library for Python. I...
- Day 13: Pandas for Data Manipulation Topics to Cover: Introduction to Pandas DataFrames and Basic Operations Introduction to Pandas Pandas is a powerful data manipulation and an...
- Day 12: NumPy for Numerical Computation Topics to Cover: Introduction to NumPy Arrays and Basic Operations Introduction to NumPy NumPy is a powerful numerical computing library in...
- Day 11: Recursion and Iterators in Python Topics to Cover: Basics of Recursion and Recursive Functions Iterators, Iterable Objects, and the iter() Function Introduction to Recursion...
- Day 10: Object-Oriented Programming (OOP) in Python Topics to Cover: Classes and Objects Methods Inheritance Introduction to OOP Object-Oriented Programming (OOP) is a programming paradigm bas...
- PythonForAI Day 8: Advanced Data Structures Welcome to Day 8 of PythonForAI! Today, we will delve into advanced data structures, specifically sets and advanced list comprehensions. The...