Loading...
Loading...

Error Handling in Python

Error handling in Python helps make programs more reliable by letting us manage errors when they occur. Using try/except blocks and assertions, we can prevent programs from crashing unexpectedly.

1. The try/except Block

The try and except keywords help us catch and handle errors in Python. By putting code that might cause an error inside a try block, we can catch specific errors in the except block.

Example

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Explanation: If dividing by zero causes an error, Python will skip the rest of the try block and run the except block, printing Cannot divide by zero!

try/except Quiz

What happens if an error occurs in a try block?

  • The program crashes immediately
  • Execution jumps to the matching except block
  • Python ignores the error

What's the purpose of specifying ZeroDivisionError in the except clause?

  • To make the code run faster
  • To only catch that specific type of error
  • To automatically fix division errors

2. Catching Different Errors

We can handle multiple errors by using different except blocks for each error type.

Example

try:
    my_list = [1, 2, 3]
    print(my_list[5]) # IndexError
except IndexError:
    print("Index is out of range!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

Explanation: Here, we handle both IndexError and ZeroDivisionError. If we try to access an index that doesn't exist, it will print Index is out of range!

Multiple Errors Quiz

What happens if an error occurs that doesn't match any except blocks?

  • The program crashes with that error
  • Python silently ignores it
  • It goes to the first except block

How can you catch all possible exceptions?

  • except AllErrors:
  • except Exception:
  • except *:

3. The else and finally Blocks

The else block runs only if no errors occur, while finally runs no matter what.

Example

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("Division successful:", result)
finally:
    print("This will always run.")

Explanation: else runs if there is no error. finally runs whether or not an error occurred, often used for cleanup tasks.

else/finally Quiz

When does the else block execute?

  • When no exceptions occur
  • When an exception occurs
  • Before the try block

What is the most common use of the finally block?

  • To handle specific errors
  • For cleanup code that must run
  • To skip error handling

4. Using Assertions

assert is used to test conditions and stop the program if the condition is False. It is helpful for debugging by ensuring assumptions are correct.

Example

def get_positive_number(num):
    assert num > 0, "Number must be positive"
    return num

print(get_positive_number(5))   # Works fine
print(get_positive_number(-2))  # Raises AssertionError

Explanation: If num is not positive, assert will raise an AssertionError with the message "Number must be positive".

Assertions Quiz

What happens when an assert condition is False?

  • AssertionError is raised
  • The program continues silently
  • Python automatically fixes the value

When should you use assert statements?

  • For handling expected runtime errors
  • For debugging and catching programming errors
  • To validate user input
0 Interaction
2.3K Views
Views
17 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home