OOP & Advanced Python

Exception Handling

01 · What is Exception Handling? File · Exception Handling · 1 of 12

What is Exception Handling?

Exception handling helps a program respond safely when something unexpected happens, instead of suddenly stopping.

Layman Example

You are withdrawing money from an ATM. Possible problems:

  1. You enter the wrong PIN
  2. Your account has insufficient balance
  3. The ATM has no cash
  4. The banking server is unavailable

The ATM should not switch off because of these problems. It should display a helpful message.

Try the operation → If a problem occurs, handle it → Continue or close the program safely

02 · What is an Exception? File · Exception Handling · 2 of 12

What is an Exception?

An exception is an error that occurs while the program is running.

Python
number = 10 / 0
Error
ZeroDivisionError: division by zero
Python
age = int("twenty")
Error
ValueError: invalid literal for int() with base 10: 'twenty'
03 · Types of Errors File · Exception Handling · 3 of 12

Types of Errors

1. Syntax Error

The program does not follow Python grammar.

Python
if age > 18
    print("Eligible")
Error
SyntaxError: expected ':'

2. Runtime Error (Exception)

The syntax is correct, but an error occurs during execution.

Python
print(10 / 0)
Error
ZeroDivisionError: division by zero

3. Logical Error

The program runs, but the answer is wrong.

Python
price = 1000
discount = 10
final_price = price - discount
print(final_price)
Output
990
Here 10 should be treated as 10%, but the program subtracts 10.
Exception handling mainly handles runtime errors.
04 · try and except File · Exception Handling · 4 of 12

Basic try and except

try:
  # risky code
except:
  # code to handle the problem

Python
try:
  number = int(input("Enter a number: "))
  result = 100 / number
  print(result)
except:
  print("Something went wrong")
Output (when user enters 0)
Enter a number: 0
Something went wrong
If the user enters 0, the program does not crash.
However, using only except: is usually not recommended because it hides the actual reason.
05 · Specific Exceptions File · Exception Handling · 5 of 12

Handling Specific Exceptions

Python
try:
  number = int(input("Enter a number: "))
  result = 100 / number
  print("Result:", result)
except ValueError:
  print("Please enter numbers only")
except ZeroDivisionError:
  print("Zero is not allowed")
Output (when user enters 6)
Enter a number: 6
Result: 16.666666666666668
Why specific exceptions are better:
1. Users receive meaningful messages
2. Developers can understand the exact problem
3. Unrelated errors are not silently hidden
06 · else and finally File · Exception Handling · 6 of 12

Complete Structure: try / except / else / finally

  • try → contains code that might fail
  • except → runs when an exception occurs
  • else → runs only when no exception occurs
  • finally → runs whether an exception occurs or not
Python
try:
  amount = float(input("Enter the withdrawal amount: "))
  balance = 10000
  remaining_balance = balance - amount
except ValueError:
  print("Please enter a valid amount")
else:
  print("Withdraw successfully.")
  print("Remaining balance:", remaining_balance)
finally:
  print("Thank you for using our ATM")
Output (example)
Enter the withdrawal amount: 12000
Withdraw successfully.
Remaining balance: -2000.0
Thank you for using our ATM
finally is mainly used for cleanup activities:
closing a file, closing a database connection, releasing a network connection, etc.
07 · raise Statement File · Exception Handling · 7 of 12

The raise Statement

raise is used to manually generate an exception when a business rule is violated.

Python
def withdraw(balance, amount):
  if amount > balance:
    raise ValueError("Insufficient balance")
  return balance - amount
raise allows you to report a problem in a controlled way.
08 · Custom Exceptions File · Exception Handling · 8 of 12

Custom Exceptions

We create our own exception classes to give meaningful names to application-specific problems.

Python
class BankCampaignError(Exception):
  pass

class DatasetFileError(BankCampaignError):
  pass

class EmptyDatasetError(BankCampaignError):
  pass

class SchemaValidationError(BankCampaignError):
  pass

class DataQualityError(BankCampaignError):
  pass

class PipelineExecutionError(BankCampaignError):
  pass
Custom exceptions make error messages clearer and help us handle different problems separately.
09 · Real World Pandas Example File · Exception Handling · 9 of 12

Real World Pandas Example

Suppose we need to read a customer CSV file and handle multiple possible problems.

Python
import pandas as pd

try:
  bank = pd.read_csv("/content/bank_market.csv")
  required_columns = ["age", "job", "default"]
  missing_columns = [
      column for column in required_columns
      if column not in bank.columns
  ]
  if missing_columns:
    raise ValueError(f"Missing required columns: {missing_columns}")
except FileNotFoundError:
  print("Bank market file was not found")
except pd.errors.EmptyDataError:
  print("The CSV file is empty")
except pd.errors.ParserError:
  print("The CSV file format is incorrect")
except ValueError as error:
  print("Data validation failed:", error)
else:
  print("Customer data loaded successfully.")
  print(bank.head())
finally:
  print("CSV processing completed")
Output
Customer data loaded successfully.
   Cust_num  age           job  marital  education default  balance housing  \
0         1   58    management  married   tertiary      no     2143     yes   
1         2   44    technician   single  secondary      no       29     yes   
2         3   33  entrepreneur  married  secondary      no        2     yes   
3         4   47   blue-collar  married    unknown      no     1506     yes   
4         5   33       unknown   single    unknown      no        1      no   

  loan  contact  day month  duration  campaign  pdays  previous poutcome   y  
0   no  unknown    5   may       261         1     -1         0  unknown  no  
1   no  unknown    5   may       151         1     -1         0  unknown  no  
2  yes  unknown    5   may        76         1     -1         0  unknown  no  
3   no  unknown    5   may        92         1     -1         0  unknown  no  
4   no  unknown    5   may       198         1     -1         0  unknown  no  
CSV processing completed
This handles: missing file, empty file, incorrect CSV structure, missing columns, and invalid data.
10 · Logging Exceptions File · Exception Handling · 10 of 12

Logging Exceptions

In production applications, errors should be recorded instead of only printed.

Python
import logging

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

try:
  result = 100 / 0
except ZeroDivisionError:
  logging.exception("Division operation failed")
  print("Unable to complete the calculation")
Output
Unable to complete the calculation
logging.exception() records: date & time, error message, exception type, and complete traceback.
11 · Retry Mechanism File · Exception Handling · 11 of 12

Retry Mechanism

Some operations can temporarily fail (for example API or database connections).

Python
import time

def connect_to_server():
  raise ConnectionError("Server is unavailable.")

maximum_attempts = 3
for attempt in range(1, maximum_attempts + 1):
  try:
    connect_to_server()
    print("Connected successfully")
    break
  except ConnectionError as error:
    print(f"Attempt {attempt} failed:", error)
    if attempt == maximum_attempts:
      print("All connection attempts failed")
    else:
      time.sleep(2)
Output
Attempt 1 failed: Server is unavailable.
Attempt 2 failed: Server is unavailable.
Attempt 3 failed: Server is unavailable.
All connection attempts failed
12 · Summary & Interview Qs File · Exception Handling · 12 of 12

Summary

  • try → attempt the work
  • except → manage the problem
  • else → confirms success
  • finally → complete the cleanup
  • raise → report a business rule violation
  • Custom exception → give the problem a meaningful name

Interview Questions

  1. What is the difference between an error and an exception?
    An error is a general problem. An exception is a runtime problem that can usually be detected and handled.
  2. What is the difference between else and finally?
    else runs only when no exception occurs. finally runs whether an exception occurs or not.
  3. Can one try have multiple except blocks?
    Yes. This allows different exception types to be handled safely.
  4. What does raise do?
    It manually generates an exception.
  5. Why create custom exceptions?
    They provide meaningful names for application-specific problems (e.g. InsufficientBalanceError).
Home Exception Handling

Exception Handling in Python

Learn how to handle runtime errors safely using try, except, else, finally, raise and custom exceptions.

Select any topic from the left sidebar to begin.


Start Learning →