Skip to content
Home » Exception Handling: Exceptions

Exception Handling: Exceptions


Exception Handling in Python – Introduction to Exceptions

When a program runs, it may face unexpected situations such as:

  • A file not found
  • Dividing a number by zero
  • Wrong input type
  • Accessing an undefined variable
  • Out-of-range index

These situations cause the program to stop suddenly with an error message.
Such runtime errors are called Exceptions.


What is an Exception? (Exam Definition)

An exception is an error that occurs during the execution of a program, which disrupts the normal flow of instructions.
Python stops the program and displays an error message.

Exceptions are not syntax errors; they occur at runtime.


Examples of Common Exceptions

ExceptionWhen it occurs
ZeroDivisionErrorWhen dividing by zero
TypeErrorWrong data type used
NameErrorUsing an undefined variable
IndexErrorAccessing index out of range
ValueErrorWrong value given
FileNotFoundErrorFile does not exist
KeyErrorKey not found in dictionary
ImportErrorModule not found

Example of an Exception

Example 1: Division by Zero

a = 10
b = 0
print(a / b)

Output:

ZeroDivisionError: division by zero

Example 2: Invalid Index

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

Output:

IndexError: list index out of range

Why Do Exceptions Occur?

Exceptions happen due to:

✔ Invalid operations
✔ Unexpected user input
✔ Missing resources (files, internet, etc.)
✔ Logical mistakes in code
✔ External errors (network failure, hardware issues)


Impact of Exceptions

If an exception occurs and is not handled, the program will:

❌ Crash
❌ Stop execution
❌ Show error message

In real applications (banking, gaming, web apps), crashes are unacceptable!


Why Do We Need Exception Handling?

Exception handling is used to:

✔ Prevent sudden program crashes
✔ Provide meaningful error messages
✔ Allow the program to continue execution
✔ Handle predictable runtime mistakes safely


Normal Flow vs Exception Flow

Normal Flow:

Program executes all statements successfully.

Exception Flow:

If an error occurs:

  1. Python stops executing
  2. Throws an exception
  3. If not handled → program terminates
  4. If handled → program continues

Exception Handling Keywords (Overview)

Python provides the following keywords:

KeywordPurpose
tryCode that may cause an exception
exceptHandles the exception
elseExecutes if no exception occurs
finallyExecutes always, clean-up code
raiseManually raise an exception

(We will discuss these in detail later.)


Simple Example of Handling an Exception

try:
    x = 10 / 0
except:
    print("Error: Cannot divide by zero!")

Output:

Error: Cannot divide by zero!

Program does not crash — exception is handled safely.


Benefits of Exception Handling

✔ Graceful handling of errors
✔ Prevents program termination
✔ Provides debugging information
✔ Makes code more reliable and robust
✔ Useful in user-input validation, file handling, networks, databases


Exam-Ready Definition

An exception is a runtime error that interrupts the normal flow of a program. Exception handling allows the programmer to detect, handle, and recover from such errors using try-except blocks, preventing the program from crashing.