Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

MODULE 8: Exception Handling & Debugging

Exception handling helps a program handle runtime errors gracefully instead of crashing. Debugging helps identify and fix issues efficiently.

1. Errors vs Exceptions

Brief

  • Errors → Problems that stop the program from running
  • Exceptions → Runtime issues that can be handled using code

Errors (Cannot be Handled Easily)

Occur due to syntax or logical mistakes.

if True
    print("Error")   # SyntaxError

Exceptions (Can Be Handled)

Occur during execution.

print(10 / 0)   # ZeroDivisionError

Key Difference

ErrorsExceptions
Compile-time / logicalRuntime
Program crashesCan be handled
SyntaxErrorZeroDivisionError

2. try, except, else, finally

Brief

Used to catch and handle exceptions.


Syntax

try:
    risky_code
except ExceptionType:
    handling_code
else:
    executes_if_no_exception
finally:
    always_executes

Basic Example

try:
    num = int(input("Enter number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid input")

else Block

Runs only when no exception occurs.

try:
    print("Hello")
except:
    print("Error")
else:
    print("No error occurred")

finally Block

Always executes (used for cleanup).

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

3. Multiple Exceptions

Brief

Handling multiple exception types separately or together.


Multiple except Blocks

try:
    a = int(input("Enter number: "))
    b = int(input("Enter number: "))
    print(a / b)
except ZeroDivisionError:
    print("Division by zero")
except ValueError:
    print("Invalid input")

Single except for Multiple Exceptions

try:
    print(int("abc") / 2)
except (ValueError, ZeroDivisionError):
    print("Error occurred")

4. Custom Exceptions

Brief

User-defined exceptions are created for business logic validation.


Creating Custom Exception

class AgeError(Exception):
    pass

Raising Custom Exception

def check_age(age):
    if age < 18:
        raise AgeError("Age must be 18 or above")
    print("Access granted")

try:
    check_age(16)
except AgeError as e:
    print(e)

Real-World Use Cases

  • Banking systems
  • Login validation
  • E-commerce checkout rules

5. Logging

Brief

Logging records program execution details for debugging and monitoring.


Why Logging Over print()?

  • Stores logs permanently
  • Different severity levels
  • Used in production systems

Logging Levels

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • CRITICAL

Basic Logging Example

import logging

logging.basicConfig(level=logging.INFO)
logging.info("Program started")
logging.error("An error occurred")

Logging to File

logging.basicConfig(
    filename="app.log",
    level=logging.DEBUG,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

logging.debug("Debugging details")

6. Debugging Techniques

1. Using print()

print("Value of x:", x)

2. Using debugger (pdb)

import pdb
pdb.set_trace()

3. IDE Debugger

  • VS Code / PyCharm
  • Breakpoints
  • Step into / step over

4. Reading Traceback

  • Last line shows the actual error
  • Follow call stack top to bottom

7. Common Python Errors

SyntaxError

if True
    print("Error")

IndentationError

if True:
print("Error")

TypeError

"10" + 5

ValueError

int("abc")

NameError

print(x)

IndexError

lst = [1, 2]
print(lst[5])

KeyError

d = {"a": 1}
print(d["b"])

Real-World Example: ATM Program

try:
    balance = 5000
    amount = int(input("Enter amount: "))
    if amount > balance:
        raise Exception("Insufficient balance")
    print("Withdrawal successful")
except Exception as e:
    print("Error:", e)
finally:
    print("Thank you for using ATM")

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥