⬅ Previous Next ➡

Exception Handling

Errors vs Exceptions (Basics)
  • Error: problem in program that stops execution (e.g., syntax mistake).
  • Exception: runtime error that can be handled using try-except.
  • Examples of exceptions: ZeroDivisionError, ValueError, TypeError, FileNotFoundError.
# Syntax Error example (cannot be handled by try-except)
# if True
#     print("Hello")
Common Runtime Exceptions
  • ZeroDivisionError → divide by zero
  • ValueError → wrong value conversion
  • TypeError → wrong type operation
  • IndexError → invalid index in list/tuple
  • KeyError → missing key in dictionary
  • FileNotFoundError → file not found
# Example
print(10 / 0)   # ZeroDivisionError
try-except Block (Basic)
  • try contains risky code.
  • except handles the exception and prevents crash.
try:
    a = int(input("Enter a number: "))
    print(10 / a)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Enter a valid integer")
Multiple Exceptions (Single except)
  • Handle multiple exceptions using a tuple in one except block.
try:
    a = int(input("Enter a number: "))
    print(10 / a)
except (ZeroDivisionError, ValueError):
    print("Invalid input or division by zero")
Catching Exception as Variable
  • Use as to store error message in a variable.
  • Useful for debugging/logging.
try:
    x = int("abc")
except Exception as e:
    print("Error:", e)
finally Block
  • finally always runs (error or no error).
  • Used for cleanup like closing file, database connection, etc.
try:
    f = open("data.txt", "r")
    print(f.read())
except FileNotFoundError:
    print("File not found")
finally:
    # safe close
    try:
        f.close()
    except:
        pass
raise Keyword (Throwing Exceptions)
  • raise is used to manually throw an exception.
  • Used when input/condition is invalid.
age = int(input("Enter age: "))

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

print("Age:", age)
Custom Exceptions (User-Defined)
  • Create your own exception class by inheriting from Exception.
  • Use when you want meaningful errors for your project.
class InvalidMarksError(Exception):
    pass

marks = int(input("Enter marks: "))

try:
    if marks < 0 or marks > 100:
        raise InvalidMarksError("Marks must be between 0 and 100")
    print("Marks:", marks)
except InvalidMarksError as e:
    print("Custom Error:", e)
⬅ Previous Next ➡