PythonIntroduction to Exceptions

Introduction to Exceptions in Python

with clear explanations and example programs — same format and style:


Introduction to Exceptions in Python

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

In Python: Errors are represented as exception objects If an exception occurs and is not handled, the program terminates with an error message Python provides a powerful way to handle exceptions using try, except blocks


Why Handle Exceptions?

ReasonBenefit
Graceful Error HandlingPrevent crashes and unexpected termination
User-friendly MessagesDisplay meaningful error messages
Maintain Program StabilityKeep application running smoothly
Handle Unexpected InputsManage edge cases without failure

Common Exceptions in Python

Exception TypeMeaning
ZeroDivisionErrorDivision by zero
TypeErrorInvalid type operation
ValueErrorInvalid value
IndexErrorIndex out of range
KeyErrorMissing key in dictionary
FileNotFoundErrorFile not found

Example 1: Unhandled Exception

example1_unhandled.py
a = 5 / 0
output.txt
ZeroDivisionError: division by zero

Explanation: Division by zero causes an exception and the program stops execution.


Example 2: Basic Exception Handling

example2_basic_handling.py
try:
    result = 10 / 0
except ZeroDivisionError:
    print("You cannot divide by zero!")
output.txt
You cannot divide by zero!

Explanation: The program does not crash — the exception is handled.


Example 3: Handling Multiple Exceptions

example3_multiple.py
try:
    num = int("abc")
except ValueError:
    print("Invalid conversion!")
except ZeroDivisionError:
    print("Division by zero!")
output.txt
Invalid conversion!

example4_generic.py
try:
    x = undefined_variable
except Exception as e:
    print("Error occurred:", e)
output.txt
Error occurred: name 'undefined_variable' is not defined

How Exception Handling Works

try:
    # Code that may raise an exception
except ExceptionType:
    # Code that runs if exception occurs
else:
    # Code that runs if no exception occurs
finally:
    # Code that always runs (cleanup)

Key Points

Exceptions are runtime errors that can disrupt the program tryexcept block is used to handle exceptions Multiple exceptions can be handled finally block always runs — used for cleanup (e.g., closing files)


Summary

  • Exceptions help manage error-prone situations gracefully
  • Without handling, exceptions terminate the program
  • Use tryexceptfinally for robust error handling
  • Common exceptions: ZeroDivisionError, ValueError, IndexError, etc.

Next, we will cover Try, Except, Else, Finally in more detail — and see how you can structure robust error-handling logic in Python.