Saturday , December 5 2026
Python Exception Handling Handling an Exception Using Try-Except Clause, User-Defined Exceptions

Python Exceptions

Updated: 28 November 2026Level: BeginnerReading time: about 10 minutesPython 3.8+

An exception is an error that happens while a program is running. Instead of letting the program crash, you can catch the exception and handle it, for example by showing a friendly message or using a default value.

What You Will Learn

  • try, except, else and finally
  • Catching specific exceptions
  • Raising your own exceptions
  • Common built-in exceptions

Prerequisites

Python Functions.

Without Handling

Example
print(10 / 0)

Explanation: The program stops at this line and nothing after it runs.

Output
ZeroDivisionError: division by zero

try and except

Example
try:
    num = int(input('Enter a number: '))
    print(100 / num)
except ValueError:
    print('Please enter a valid number')
except ZeroDivisionError:
    print('Cannot divide by zero')

Explanation: Python runs the try block. If an error happens, it jumps to the matching except block. Catch specific exceptions so real bugs are not hidden.

else and finally

Example
try:
    f = open('data.txt', encoding='utf-8')
except FileNotFoundError:
    print('File not found')
else:
    print(f.read())
    f.close()
finally:
    print('Done')

Explanation: else runs only if no exception happened. finally always runs, which is useful for cleanup.

Getting the Error Message

Example
try:
    int('abc')
except ValueError as e:
    print('Error:', e)
Output
Error: invalid literal for int() with base 10: 'abc'

Raising Exceptions

Example
def set_age(age):
    if age < 0:
        raise ValueError('Age cannot be negative')
    return age

try:
    set_age(-5)
except ValueError as e:
    print(e)
Output
Age cannot be negative

Custom Exceptions

Example
class InsufficientBalance(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientBalance(f'Balance is only {balance}')
    return balance - amount

Common Exceptions

Exception When it happens
ValueError Right type, wrong value: int(‘abc’)
TypeError Wrong type: ‘a’ + 1
ZeroDivisionError Divide by zero
IndexError List index out of range
KeyError Missing dictionary key
FileNotFoundError File does not exist
AttributeError Object has no such attribute
ImportError / ModuleNotFoundError Module cannot be imported

Common Errors

Problem Cause and fix
Bare except: hides bugs Catch specific exceptions, or at least except Exception as e and log e.
Code after the error never runs Move the risky line into try, and continue in else.

Practice Exercises

  1. Keep asking for input until a valid integer is entered.
  2. Safely read a file and print a message if it is missing.
  3. Create a custom exception for invalid marks (outside 0–100).

Interview Questions

Q: What is the purpose of finally?
It always runs, used for cleanup like closing files.

Q: Difference between an error and an exception?
Syntax errors stop the code before running; exceptions happen at runtime and can be handled.

Summary

Wrap risky code in try, catch specific exceptions, use else for the success path and finally for cleanup, and raise your own exceptions for invalid input.

Next: Python File Handling · Python Functions

About Machine Learning

Check Also

Python Inheritance: super(), Method Overriding and MRO

Python inheritance with super(), method overriding, isinstance, multiple inheritance and the method resolution order.