19. Error and exception handling

Quiz: 0/5

An error is a problem that occurs when running your program, while an exception is a special type of error that you can catch and handle in your program. Errors can occur for various reasons, like wrong input or trying to divide by zero.

For example:

  • Trying to divide a number by zero.
  • Trying to access a file that doesn’t exist.
  • Trying to use a variable that hasn’t been defined.

How to handle errors in Python

Python provides a way to handle errors using try, except, else, and finally blocks. This approach helps you handle errors gracefully and continue your program without crashing.

The try block

The try block is used to write code that might cause an error. If an error occurs, Python will stop executing the rest of the code in the try block and move to the except block.

try:
    # Code that might cause an error
    result = 10 / 0  # Division by zero
except ZeroDivisionError:
    # Handling the error
    print("You can't divide by zero!")

The except block

The except block catches the error and allows you to handle it. In this case, we're catching a ZeroDivisionError and printing a friendly message.

The else block

The else block runs if there was no error in the try block. It’s an optional block and can be used for code that should run if everything went smoothly.

try:
    result = 10 / 2
except ZeroDivisionError:
    print("You can't divide by zero!")
else:
    print("Division successful:", result)

The finally block

The finally block always runs, regardless of whether an exception occurred or not. It’s usually used for clean-up tasks (like closing a file or releasing resources).

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    print("Closing the file.")
    file.close()  # Ensures the file is closed even if an error occurred

Raising Exceptions

Sometimes, you may want to raise your own exceptions if something goes wrong in your program. You can do this using the raise keyword.

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    else:
        print("Your age is:", age)

try:
    check_age(-5)
except ValueError as e:
    print("Error:", e)

Common Python Exceptions

Here are some common exceptions you might encounter in Python:

  • ZeroDivisionError: Occurs when trying to divide by zero.
  • FileNotFoundError: Raised when trying to open a file that doesn't exist.
  • ValueError: Raised when a function receives an argument of the correct type, but an inappropriate value.
  • IndexError: Raised when trying to access an index that is out of range in a list.

Recap

  • Use the try block for code that may cause an error.
  • Use the except block to catch and handle exceptions.
  • Use the else block for code that should run if no error occurs.
  • Use the finally block for cleanup tasks.
  • Raise your own exceptions using raise when necessary.

Hands-On Practise

Exercise: Division with predefined values

Task:
Write a Python program that performs division using predefined values for the numerator and denominator. Handle the following cases:

  1. If the denominator is zero, handle the ZeroDivisionError and print a message like "You can't divide by zero!"
  2. If any of the values are not valid numbers (e.g., strings), handle the ValueError and print a message like "Invalid number!"
  3. If the division is successful, print the result.

You can use the following values for the exercise:

  • Numerator: 100
  • Denominators: 2, 0, 'abc' (non-numeric string)

Instructions:

  1. Use the try, except, else, and finally blocks to handle exceptions.
  2. Ensure the program doesn't crash and provides a friendly message for different types of errors.
  3. Print the result if the division is successful.
Output:

Quizzes: 0/5

Question 1:

What does the 'except' block do in Python exception handling?

  • It raises an error.
  • It catches and handles the error.
  • It executes code before the 'try' block.
  • It defines the function that causes the error.

Question 2:

What happens if no error occurs in the 'try' block?

  • The 'except' block is executed.
  • The 'else' block is executed.
  • The program will stop.
  • The 'finally' block is skipped.

Question 3:

What is the purpose of the 'finally' block in Python exception handling?

  • It runs code that should always be executed, whether or not an exception occurred.
  • It raises an exception.
  • It checks for errors before the 'try' block.
  • It catches exceptions from the 'try' block.

Question 4:

Which error is raised when trying to divide by zero in Python?

  • ZeroDivisionError
  • ValueError
  • TypeError
  • IndexError

Question 5:

How can you raise your own exception in Python?

  • Using the 'raise' keyword.
  • Using the 'throw' keyword.
  • Using the 'exception' function.
  • Using the 'error' function.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonIntroduction to Python FunctionsNext lessonPython Modules and Libraries