DEV Community

M.T.Ramkrushna
M.T.Ramkrushna

Posted on

PYTHON ESSENTIALS FOR AI/ML(Error Handling)

⚡ What is Error Handling?

Error handling means predicting, catching, and responding to errors so your program doesn’t crash.

Real-life analogy:
Imagine you’re ordering food online. If the restaurant is closed, the app doesn’t crash — it shows “Restaurant unavailable”.
That’s error handling.


⚡ Types of Errors in Python

1️⃣ Syntax Errors

  • Mistakes in code structure.
  • Program won't run until fixed.

Example:

print("hello"
Enter fullscreen mode Exit fullscreen mode

Missing ) → syntax error.


2️⃣ Runtime Errors (Exceptions)

  • Code is syntactically correct but fails during execution.

Example:

10 / 0   # ZeroDivisionError
Enter fullscreen mode Exit fullscreen mode

Real-life example:
Trying to withdraw ₹2000 when your wallet has ₹500.


3️⃣ Logical Errors

  • No crash, but wrong output due to incorrect logic.

Example:

# Intended: average of two numbers
avg = (a + b) / 2   # correct
avg = a + b / 2     # wrong → no error but wrong logic
Enter fullscreen mode Exit fullscreen mode

Real-life example:
Setting an alarm for 6 PM instead of 6 AM — phone doesn’t complain, but logic is wrong.


⚡ The try / except Block

Basic structure:

try:
    # code that might fail
except:
    # what to do if it fails
Enter fullscreen mode Exit fullscreen mode

⚡ Catching Specific Exceptions (best practice)

Why specific?
It’s like telling the delivery app what to do for each issue:

  • Restaurant closed
  • Payment failed
  • Wrong address

Example:

try:
    num = int(input("Enter number: "))
    result = 10 / num
except ValueError:
    print("Please enter a valid number.")
except ZeroDivisionError:
    print("Number cannot be zero.")
Enter fullscreen mode Exit fullscreen mode

else Block (runs when no error occurs)

Real-life analogy:
If payment is successful, THEN show “Order confirmed”.

try:
    f = open("data.txt")
except FileNotFoundError:
    print("File missing!")
else:
    print("File opened successfully!")
    f.close()
Enter fullscreen mode Exit fullscreen mode

finally Block (ALWAYS runs)

Real-life analogy:
After cooking, you always turn off the gas — whether food is burnt, undercooked, or perfect.

try:
    f = open("data.txt")
    content = f.read()
except FileNotFoundError:
    print("File not found")
finally:
    print("Cleaning up...")
Enter fullscreen mode Exit fullscreen mode

⚡ Raising Your Own Errors (raise)

You can trigger errors when invalid data is detected.

Real-life example:
If someone tries to book 12 tickets (but limit is 10), you show an error.

def book_tickets(n):
    if n > 10:
        raise ValueError("Cannot book more than 10 tickets")
    return "Tickets booked!"

book_tickets(12)
Enter fullscreen mode Exit fullscreen mode

⚡ Custom Exceptions

Useful in large applications (AI pipelines, payment apps, etc):

Real-life example:
You create a custom error: LowBatteryError.

class LowBatteryError(Exception):
    pass

def start_camera(battery):
    if battery < 10:
        raise LowBatteryError("Battery too low!")
    print("Camera started.")

start_camera(5)
Enter fullscreen mode Exit fullscreen mode

⚡ Real-Life Relatable Examples

✔ Example 1: ATM Machine

ATM checks:

  • Card validity → ValueError
  • Wrong pin → AuthenticationError (custom)
  • Low balance → InsufficientFundsError
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Balance too low.")
    return balance - amount

try:
    new_balance = withdraw(500, 1000)
except InsufficientFundsError as e:
    print(e)
Enter fullscreen mode Exit fullscreen mode

✔ Example 2: AI Model Loading (ML Example)

try:
    model = load_model("model.pkl")
except FileNotFoundError:
    print("Model missing! Download it again.")
Enter fullscreen mode Exit fullscreen mode

✔ Example 3: Reading JSON Config

import json

try:
    data = json.loads('{"name": "Ali"')   # missing ending }
except json.JSONDecodeError:
    print("Invalid config file format!")
Enter fullscreen mode Exit fullscreen mode

⚡ Quick Summary (for memory)

  • try → attempt
  • except → recovery
  • else → success block
  • finally → cleanup
  • raise → throw custom error
  • Custom Exceptions → your own meaningful error types

Top comments (0)