Learn python this summer Day 6: Error Handling

Welcome back! Yesterday, we learned about functions in Python. Today, we’ll explore error handling, which is crucial for writing robust and reliable programs. By the end of this day, you’ll know how to handle errors gracefully in your Python programs. Let’s get started!

What is Error Handling?
Error handling allows you to anticipate and manage errors that may occur during the execution of your program. This helps prevent your program from crashing and provides a way to handle unexpected situations.

Types of Errors
Syntax Errors: Occur when the code is not written correctly.
Runtime Errors: Occur during the execution of the program.
Logical Errors: Occur when the code doesn’t produce the expected result.
Try and Except
The try and except blocks are used to catch and handle exceptions. Here’s the basic syntax:

python
Copy code
try:

Code that may cause an error

except ErrorType:

Code to handle the error

Example:

python
Copy code
try:
result = 10 / 0
except ZeroDivisionError:
print("You can’t divide by zero!")
Else and Finally
You can also use else and finally blocks with try and except:

else: Executes if no exception occurs.
finally: Executes no matter what, even if an exception occurs.
Example:

python
Copy code
try:
number = int(input("Enter a number: "))
except ValueError:
print("That’s not a valid number!")
else:
print(f"You entered {number}.")
finally:
print("This will always execute.")
Custom Exceptions
You can create your own custom exceptions by subclassing the Exception class.

Example:

python
Copy code
class MyCustomError(Exception):
pass

try:
raise MyCustomError("An error occurred!")
except MyCustomError as e:
print(e)
Practice Time!
Let’s put what we’ve learned into practice. Write a Python program that uses try, except, else, and finally blocks to handle errors.

python
Copy code
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: You can’t divide by zero!")
else:
print(f"Result: {result}")
finally:
print("Execution complete.")

Test the function

divide_numbers(10, 2)
divide_numbers(10, 0)
Conclusion
Great job today! You’ve learned how to handle errors in Python, making your programs more robust and user-friendly. Tomorrow, we’ll dive into modules and packages, which will help you organize and reuse your code even more efficiently. Keep practicing and having fun coding!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *