Showing posts with label error handling in python. Show all posts
Showing posts with label error handling in python. Show all posts

Tuesday, June 17, 2025

🛠️ Error Handling in Python – Catching Mistakes Like a Pro!

 Have you ever run a Python program and seen a weird red error message?

That’s Python telling you something went wrong. But don’t worry! Python also gives you tools to catch and fix those errors using something called error handling.

In this blog, you’ll learn:

  • What errors are

  • Why we need error handling

  • How to use try, except, finally

  • Some fun examples to practice


❗ What is an Error?

An error is something that breaks your program.

🔹 Two types of errors in Python:

TypeExample
Syntax ErrorForgetting a colon : in a loop
Runtime ErrorDividing by zero or accessing bad data

Example:
print("Hello)
# SyntaxError: EOL while scanning string literal x = 5 / 0 # ZeroDivisionError: division by zero

🧯 Why Use Error Handling?

If you don’t handle errors, your program will crash.
With error handling, you can:

  • Show friendly error messages 😇

  • Avoid crashing the program 💥

  • Keep your app running smoothly 🚀


🧪 The try and except Block

This is how we catch errors:

try:
# risky code x = 5 / 0 except ZeroDivisionError: print("Oops! You can't divide by zero.")

Output:

Oops! You can't divide by zero.

Python tried to divide, but when it hit an error, it jumped to the except block.


🎯 Example: User Input Error

try:
num = int(input("Enter a number: ")) print("You entered:", num) except ValueError: print("That's not a valid number!")

🔁 Using finally

The finally block always runs, whether there’s an error or not.

try:
file = open("myfile.txt", "r") content = file.read() except FileNotFoundError: print("File not found!") finally: print("This runs no matter what.")

🔄 Catching Multiple Errors

try:
x = int(input("Enter number: ")) y = 10 / x except ValueError: print("That's not a number!") except ZeroDivisionError: print("Can't divide by zero!")

🧠 Pro Tip: Use else for clean execution

try:
age = int(input("Enter your age: ")) except ValueError: print("Please enter a number.") else: print("Your age is:", age)

🚨 Common Errors in Python

Error TypeDescription
ValueErrorWrong data type (e.g. text instead of number)
ZeroDivisionErrorDividing by zero
IndexErrorList index out of range
KeyErrorMissing key in dictionary
TypeErrorWrong operation on data types
FileNotFoundErrorMissing file

✅ Summary

Python’s error handling tools (try, except, else, and finally) help you write safer, more professional code.

  • Start with try and except

  • Use finally for cleanup

  • Catch specific errors to give clear messages


🧪 Practice Challenges

  1. Write a program that divides two numbers and catches divide-by-zero error.

  2. Ask the user to enter a file name. Catch FileNotFoundError.

  3. Build a calculator that handles wrong input gracefully.


🚀 Keep Learning!

Error handling is just the start. As you write bigger programs and games, you’ll use it all the time.

Keep coding, keep crashing, and keep fixing! That’s how you become a pro! 💻🔥


🚀 Exploring Gemini AI and Python: A Beginner’s Guide for School Students

 Have you ever wondered how your favorite apps recognize your face, suggest videos, or even talk back like a real human? Welcome to the worl...