Python Programming Exception Handling
Robust Programming Error Management

Python Exception Handling Complete Guide

Learn Python exception handling - try-except blocks, finally clause, custom exceptions with practical examples, patterns, and real-world applications for robust error management.

try-except

Catch and handle errors

Custom Exceptions

Create your own error types

finally Clause

Cleanup operations

raise Statement

Throw exceptions

What is an Exception?

An exception is an error that occurs during program execution.

Python exceptions overview: runtime errors such as ZeroDivisionError and TypeError, exception objects, and why programs need try except handling
Exceptions: When something goes wrong at runtime, Python raises an exception—your code can catch it or let it stop the program.
Example
print(10 / 0)

Output: ZeroDivisionError: division by zero

Without exception handling, the program crashes.

Python exception handling flowchart: try block runs guarded code, except catches matching errors, optional else runs if no error, finally always runs
Control flow: Typical path through try → success or except → optional else / finally for cleanup.

Why Use Exception Handling?

  • Prevent program crashes
  • Display user-friendly error messages
  • Handle unexpected situations
  • Improve program reliability

Basic Syntax

try-except syntax
try:
    # risky code
except:
    # code to handle error
Basic example
try:
    num = 10 / 0
except:
    print("Error occurred")

Output: Error occurred

Flow of Exception Handling

1. try and except

The try block contains code that may produce an error. The except block handles the error.

try/except example
try:
    a = int(input("Enter number: "))
    print(100 / a)
except:
    print("Invalid input")

Handling Specific Exceptions

Specific exception blocks
try:
    num = int(input("Enter number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Please enter valid integer")

Common Python Exceptions

ExceptionDescription
ZeroDivisionErrorDivision by zero
ValueErrorInvalid value
TypeErrorWrong data type
IndexErrorInvalid list index
KeyErrorInvalid dictionary key
NameErrorVariable not defined
FileNotFoundErrorFile does not exist

Multiple Exceptions in One Block

Tuple except
try:
    x = int(input())
    print(10 / x)
except (ValueError, ZeroDivisionError):
    print("Error occurred")

Using else Block

else example
try:
    num = int(input("Enter number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Program executed successfully")

Using finally Block

finally example
try:
    file = open("data.txt")
except FileNotFoundError:
    print("File not found")
finally:
    print("Execution completed")

try-except-else-finally Structure

Full structure
try:
    num = int(input())
except ValueError:
    print("Invalid input")
else:
    print("No exception")
finally:
    print("Always executed")

Raising and Custom Exceptions

Raising Exceptions

raise example
age = -5
if age < 0:
    raise ValueError("Age cannot be negative")

Custom Exceptions

Custom exception class
class InvalidAgeError(Exception):
    pass

age = -1
if age < 0:
    raise InvalidAgeError("Invalid age")

Using Exception Object

as e example
try:
    print(10 / 0)
except ZeroDivisionError as e:
    print("Error:", e)

Output: Error: division by zero

Nested try-except

Nested block example
try:
    try:
        print(10 / 0)
    except ZeroDivisionError:
        print("Inner exception handled")
except:
    print("Outer exception handled")

File Handling with Exceptions

File exception example
try:
    file = open("sample.txt", "r")
    print(file.read())
except FileNotFoundError:
    print("File does not exist")
finally:
    print("File operation completed")

Best Practices

  • Catch specific exceptions instead of generic except
  • Use finally for cleanup tasks
  • Avoid hiding errors unnecessarily
  • Write meaningful error messages
  • Use custom exceptions for large projects

Real-Life Examples

ATM Withdrawal
balance = 5000
try:
    amount = int(input("Enter withdrawal amount: "))
    if amount > balance:
        raise ValueError("Insufficient balance")
    print("Withdrawal successful")
except ValueError as e:
    print(e)
List Index Example
try:
    data = [10, 20, 30]
    print(data[5])
except IndexError:
    print("Index out of range")

Interview Questions

1. Difference between Error and Exception?
Errors are serious issues. Exceptions can be handled.

2. Difference between except and finally?
except runs only when exception occurs. finally always runs.

3. Why use custom exceptions?
For better readability and project-specific error handling.

4. Can finally run without except?
Yes.

finally without except
try:
    print("Hello")
finally:
    print("Done")

Mini Practice Programs

  • Handle divide by zero
  • Handle invalid user input
  • Handle file not found
  • Create custom exception
  • Handle list index error

Summary

  • try -> risky code
  • except -> handles errors
  • else -> runs if no error
  • finally -> always runs
  • raise -> manually create exceptions
  • Custom exceptions improve program structure