Error Handling in Python

Errors are a natural part of programming. No matter how careful you are, mistakes will happen — maybe a wrong variable name, dividing a number by zero, or trying to open a file that doesn’t exist.

Error Handling in Python

In Python, when something goes wrong, your program stops running and shows an error message (called an exception).

If you don’t handle these exceptions, your program will crash. But don’t worry — Python gives us tools to gracefully handle errors so your program can continue running.


Types of Errors in Python

Before diving into handling, let’s first see the types of errors:

  1. Syntax Errors – When you write code that Python cannot understand.
    Example: print(“Hello” # Missing closing parenthesis Output: SyntaxError: unexpected EOF while parsing
  2. Runtime Errors (Exceptions) – Errors that happen while the program is running.
    Example: print(10 / 0) Output: ZeroDivisionError: division by zero
  3. Logical Errors – The program runs but gives the wrong result because of incorrect logic.
    Example: # Intended to calculate average, but forgot parentheses avg = 10 + 20 / 2 print(avg) # Wrong result

Exception Handling with try and except

The most basic way to handle errors in Python is by using try and except.

Example:

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except:
    print("Oops! Something went wrong.")

Here’s what happens:

  • Code inside try is executed.
  • If any error occurs, Python jumps to except block instead of crashing.

Handling Specific Exceptions

Catching all errors blindly is not a good practice. Instead, you should handle specific exceptions.

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ValueError:
    print("❌ Please enter a valid number.")
except ZeroDivisionError:
    print("❌ Division by zero is not allowed.")

This way, you know exactly what went wrong.


Using else with try-except

Python also allows an else block, which runs only if no error occurs.

try:
    num = int(input("Enter a number: "))
    print("Square:", num ** 2)
except ValueError:
    print("Invalid input, please enter a number.")
else:
    print("✅ Program ran successfully!")

The finally Block

Sometimes you need code that must run no matter what — for example, closing a file or releasing resources. That’s where finally comes in.

try:
    file = open("data.txt", "r")
    print(file.read())
except FileNotFoundError:
    print("File not found.")
finally:
    print("Closing file (if opened).")

Raising Exceptions with raise

Sometimes, you may want to create your own error when a condition is not met.

age = int(input("Enter your age: "))
if age < 18:
    raise ValueError("You must be at least 18 years old.")
else:
    print("Access granted.")

Here, we forcefully raise a ValueError if the user is under 18.


Custom Exceptions

You can even define your own exception classes to make programs more readable.

class NegativeNumberError(Exception):
    pass

def check_number(num):
    if num < 0:
        raise NegativeNumberError("Negative numbers are not allowed.")
    else:
        print("Number is valid!")

try:
    check_number(-5)
except NegativeNumberError as e:
    print("❌ Error:", e)

Also Read: File Handling in Python


Best Practices for Error Handling

  1. ✅ Always catch specific exceptions (e.g., ValueError, FileNotFoundError).
  2. ✅ Use finally to clean up resources (close files, release connections).
  3. ✅ Avoid empty except: blocks — they make debugging hard.
  4. ✅ Raise meaningful errors when input is invalid.
  5. ✅ Don’t overuse exceptions for normal logic.

Mini Project: Basic Calculator with Error Handling

Let’s build a calculator that handles errors gracefully.

def calculator():
    try:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        operator = input("Choose operator (+, -, *, /): ")

        if operator == "+":
            print("Result:", num1 + num2)
        elif operator == "-":
            print("Result:", num1 - num2)
        elif operator == "*":
            print("Result:", num1 * num2)
        elif operator == "/":
            print("Result:", num1 / num2)
        else:
            print("❌ Invalid operator")
    except ValueError:
        print("❌ Please enter numbers only.")
    except ZeroDivisionError:
        print("❌ Division by zero not allowed.")
    finally:
        print("Thank you for using calculator!")

calculator()

Sample Run:

Enter first number: 10
Enter second number: 0
Choose operator (+, -, *, /): /
❌ Division by zero not allowed.
Thank you for using calculator!

Final Thoughts

Error handling makes your Python programs more reliable and professional. Instead of crashing, your code will gracefully handle problems and guide the user with helpful messages.

From basic try-except to custom exceptions, mastering error handling is a must if you want to build real-world applications.

FAQs – Error Handling in Python

  • Syntax Errors happen when your code is written incorrectly (e.g., missing colon, wrong indentation). Python won’t run until you fix it.

  • Exceptions occur while the program is running (e.g., dividing by zero, file not found). These can be handled with error handling.

You can use the raise keyword to create custom exceptions. Example:

age = -5
if age < 0:
         raise ValueError("Age cannot be negative")

finally ensures that important code (like closing a file or releasing resources) always runs, even if an error occurs.

It makes your programs more reliable, user-friendly, and professional by preventing sudden crashes and giving meaningful error messages.

What’s Next?

In the next post, we’ll learn about the Date and Time in Python

Spread the love

Leave a Comment

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

Translate »
Scroll to Top