Day 9: Exception Handling in Python – Python4AI

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!

Team
Team

This account on Doubtly.in is managed by the core team of Doubtly.

Articles: 475