Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 04

try and except Basics — Syntax for Handling Exceptions

Learn the try and except syntax — monitor risky code, catch runtime exceptions, and keep Python programs running gracefully.

Intermediate40 min
try except basics hero Module 15 Lesson 4 MahiDev

Definition: Exception handling = try (monitor) + except (respond). The goal is to replace technical crashes with messages users can understand.

What you will learn

  • Understand the try and except syntax
  • Learn how Python monitors risky code
  • See how PVM exits a try block on error
  • Build a safe division program
  • Understand else, finally, and raise at a high level

The five exception keywords

Think of exception handling as a team where each keyword has one job.

MahiDev exception team try except else finally raise

Quick summary

Keyword Purpose
try Monitor risky statements
except Catch matching exceptions
else Execute only when no exception occurs
finally Always runs (cleanup)
raise Manually create an exception

This lesson focuses on try and except.


1. Basic syntax

Every exception handling block follows the same structure.

python
try:
    # risky statements
    a = int("10")
    b = int("0")
    result = a / b

except ZeroDivisionError:
    print("Denominator cannot be zero")

except ValueError:
    print("Please enter valid numbers")

Visual structure

Basic try except structure MahiDev diagram

2. What does the try block do?

The try block is called the Exception Monitoring Block.

It tells Python:

"Watch these lines carefully. They may produce a runtime exception."

Example

python
try:
    print("Step 1")
    result = 10 / 0
    print("Step 2")  # never runs

What happens internally?

PVM execution flow Step 1 divide zero jump to except

Important rule

When an exception occurs:

  • ✅ Current line stops immediately
  • ✅ PVM exits the try block
  • ❌ Remaining lines inside try are skipped

3. What does the except block do?

The except block is called the Exception Processing Block.

Its job is to replace this:

text
ZeroDivisionError: division by zero

with this:

text
Please don't enter zero.

Visual comparison

Without except program crashes with except program continues

4. Multiple except blocks

Different errors deserve different messages.

python
# Simulated user input — no input() in browser playground
a = int("10")
b = int("0")

try:
    print(a / b)
except ValueError:
    print("Enter numbers only")
except ZeroDivisionError:
    print("Don't divide by zero")

Try changing a = int("abc") in the playground to trigger ValueError instead.

Decision flow

Multiple except blocks ValueError ZeroDivisionError match type

Python executes only the matching except block.


5. Safe division program

This is how real applications validate user input — here with fixed values instead of input().

MahiDev safe division simulate A B scenarios
python
def safe_div(a, b):
    print("Program started")
    print("Trying division:", a, "/", b)
    try:
        result = a / b
        print("Division OK:", result)
    except ZeroDivisionError:
        print("Cannot divide by zero")
    except ValueError:
        print("Invalid numbers")
    print("Program ended")

safe_div(10, 2)   # Division OK: 5.0
safe_div(10, 0)   # Cannot divide by zero

Change a or b in the playground to simulate different runtime situations.


6. Step-by-step program execution

Let's trace a real execution.

python
print("Program started")

try:
    result = 10 / 0
    print(result)  # skipped

except ZeroDivisionError:
    print("Don't enter zero")

print("Program ended")

Execution timeline

Step by step execution timeline program started except program ended

Final output

text
Program started
Don't enter zero
Program ended

Notice that print(result) never executes.


7. What if there is NO exception?

The try block simply finishes normally.

Success case 10 divide 2 vs failure 10 divide 0

Case 1 — Success:

python
try:
    print(10 / 2)
except ZeroDivisionError:
    print("Error")

Output: 5.0

Case 2 — Failure:

python
try:
    print(10 / 0)
except ZeroDivisionError:
    print("Error")

Output: Error


8. Common beginner mistakes

Beginner mistakes try without except wrong exception type

Mistake 1 — try without except:

python
try:
    print(10 / 2)
# ❌ Invalid syntax — need at least one except or finally

Mistake 2 — Wrong exception type:

python
try:
    int("abc")
except KeyError:
    print("Handled")  # ❌ ValueError is raised, not KeyError

Correct approach:

python
try:
    int("abc")
except ValueError:
    print("Please enter numbers")  # ✅ Match the class exactly

Memory map

MahiDev memory formula try exception except program continues

Interview questions

Q1. What is the purpose of a try block?

Answer: To monitor statements that may raise runtime exceptions.

Q2. What happens when an exception occurs inside try?

Answer: PVM immediately exits the try block, skips the remaining statements, and searches for a matching except.

Q3. Can one try have multiple except blocks?

Answer: Yes. Each except handles a different exception class with its own user-friendly message.


Key takeaways

  • try = Exception Monitoring Block
  • except = Exception Processing Block
  • When an exception occurs, PVM exits the try block immediately
  • Multiple except blocks allow different messages for different errors
  • Exception handling makes applications robust by preventing crashes
  • Next: else and finally Blocks — when else runs, why finally always executes, and resource cleanup patterns

Loading playground…

Check your understanding

try except basics quiz

try block is called:

1 / 10