Skip to main content

Python Exception Handling: Try, Except, Else, Finally with Examples

 

✍️Introduction:

Exception handling in Python is a mechanism used to detect and handle runtime errors so that the program can continue running smoothly.

In Python, an exception is an error that occurs during program execution. If exceptions are not handled, the program stops suddenly.

Exceptions occur when unexpected situations happen, such as dividing by zero, opening a missing file, or entering invalid input.
By using exception handling, programmers can control these errors and display meaningful messages instead of stopping the program abruptly.

Exception Handling allows us to handle errors gracefully without crashing the program.


What is an Exception?

An exception is a runtime error.

An exception is generated when Python encounters an operation it cannot perform.
When an exception occurs, Python stops the normal flow of the program and raises an error message.
Exception handling helps manage these errors so the program can continue running instead of terminating.

Examples:

  • Dividing by zero

  • Accessing invalid index

  • Using wrong data type


Common Python Exceptions :

Common Python exceptions are built-in error types that occur when a program encounters invalid operations during execution.

Exception                Description
ZeroDivisionError         Division by zero
ValueErrorInvalid value
TypeErrorWrong data type
IndexErrorInvalid index
KeyErrorKey not found

Each exception represents a specific type of error, which helps programmers identify and handle problems more easily.
By recognizing these exceptions, programs can respond properly instead of crashing unexpectedly.


Why Exception Handling is Important?

  • Prevents program crash

  • Improves user experience

  • Makes code robust

  • Used in real-world applications


Basic Exception Handling Syntax :

try: # risky code except: # error handling code

The try-except block is used to handle errors in Python and prevent the program from crashing.

The code that may cause an error is written inside the try block.
If an exception occurs, Python immediately stops executing the try block and runs the except block to handle the error safely.


Example: Handling Division Error

The risky code is placed inside the try block.
If a division by zero error occurs, Python jumps to the except block and displays an error message instead of stopping the program.

This example shows how exception handling prevents a program from crashing when a division by zero occurs.

Example:

try:      
    a = 10                                           # Assigns value to a
    b = 0                                             # Assigns value to b
    print(a / b)                                    # Causes division by zero error
except:
    print("Cannot divide by zero")    # Handles the error

Output (example):

Cannot divide by zero


"Code executed successfully" 


Using Specific Exception :

Handling a specific exception means catching a particular type of error instead of handling all errors.

Using specific exceptions like ValueError makes programs more precise and easier to debug.
It ensures that only the expected error is handled while other errors can still be detected.

Example:

try: num = int(input("Enter number: ")) # Takes input and converts to integer print(num) # Prints the number if valid except ValueError: # Handles invalid number input print("Invalid input") # Displays error message

Example Output (Invalid Input):

Enter number: abc

Invalid input


"Code executed successfully" 

Multiple Except Blocks :

Multiple except blocks allow a program to handle different types of exceptions separately.

Using multiple except blocks helps identify the exact error that occurs and handle it appropriately.
Python checks each except block in order and executes the one that matches the exception.

Example:

try: x = int("abc") # Tries to convert string to integer (causes ValueError) except ValueError: print("Value error") # Executes if ValueError occurs except TypeError: print("Type error") # Executes if TypeError occurs

Output :

Value error


"Code executed successfully" 


else Block :

The else block runs when no exception occurs in the try block.

The else block is used to execute code only if the try block runs successfully without any errors.
This helps separate normal code from error-handling code, making programs easier to understand.

Example:

try: print(10 / 2) # Divides 10 by 2 (no error) except: print("Error") # Runs only if an error occurs else: print("Success") # Runs if no exception occurs


Output :

5.0 Success


"Code executed successfully" 


finally Block :

The finally block always executes whether an exception occurs or not.

The finally block is used to run important code such as closing files or releasing resources.
It executes after the try and except blocks, ensuring cleanup operations always happen.

Example:

try: print(10 / 0) # Causes division by zero error except: print("Error occurred") # Handles the error finally: print("Program ended") # Always executes

Output :

Error occurred Program ended


"Code executed successfully" 


Raise an Exception :

Raising an exception means manually generating an error in a program using the raise keyword.

The raise statement is used when a program needs to stop execution if a certain condition is not met.
It helps enforce rules and ensures invalid data or conditions are not accepted.

Example:

age = 15           # Stores age value if age < 18:         # Checks if age is less than 18 raise Exception("Not eligible to vote") # Raises an exception with message

Output :

Exception: Not eligible to vote


"Code executed successfully" 

Note:The program stops immediately when an exception is raised.


User-Defined Exception :

A user-defined exception is a custom error created by the programmer to handle specific situations in a program.

Python allows programmers to create their own exception classes by inheriting from the built-in Exception class.
This is useful when you want to define meaningful errors for specific conditions in your application.

Example:

class MyError(Exception): # Creates a custom exception class pass # No extra code needed raise MyError("This is a custom error") # Raises the custom exception

Output :

MyError: This is a custom error


"Code executed successfully" 

Note:User-defined exceptions make programs easier to understand and debug.


Real-Life Example :

This example demonstrates how exception handling can be used in real life to prevent withdrawing more money than the available balance.

In real-world applications like banking systems, exceptions help enforce rules and prevent invalid operations.
If the withdrawal amount exceeds the balance, an exception is raised and handled gracefully instead of crashing the program.

Example:

try: balance = 5000         # Stores account balance withdraw = int(input("Enter amount: "))         # Takes withdrawal amount if withdraw > balance:         # Checks if amount exceeds balance raise Exception("Insufficient balance")    # Raises exception if true print("Withdraw successful")          # Executes if amount is valid except Exception as e:          # Catches the exception print(e)         # Prints error message

Example Output (Invalid Amount):

Enter amount: 7000 Insufficient balance

Example Output (Valid Amount):

Enter amount: 2000 Withdraw successful


"Code executed successfully" 


❌ Common Mistakes:

  • Using only except without specifying error

  • Not using finally for cleanup

  • Ignoring error messages


Difference: Error vs Exception

Errors and exceptions both indicate problems in a program, but they occur at different stages.
Errors usually happen due to mistakes in the code (like syntax errors) and prevent the program from running, while exceptions occur during execution and can be handled using exception handling techniques.

Exceptions allow programs to recover from unexpected situations, whereas errors generally need to be fixed before the program can run successfully.

      Error                               Exception           
Syntax mistake  Runtime issue
Cannot be handledCan be handled
Program won’t runProgram runs


Conclusion :

Exception handling is very important in Python programming.
It helps you write safe, stable, and professional programs.


💬 Interview Question :

What is the difference between finally and else?

Comment your answer 👇😊


📌 Related Articles



Comments

popular

What Is Python Programming? Features, Uses and Career Scope.

  ✍️ Introduction Python is one of the most popular and beginner-friendly programming languages in the world today. It is widely used for web development, data science, artificial intelligence, automation, and software development. Because of its simple syntax and powerful features, Python is an excellent choice for students, beginners, and professionals. In this article, you will learn what Python programming is, its key features, real-life uses, and the career opportunities it offers. 🧠 What Is Python Programming? Python is a high-level, interpreted programming language created to make coding easy and readable. It allows developers to write programs using simple English-like statements, which makes it ideal for beginners. Python supports multiple programming styles such as procedural, object-oriented, and functional programming. ⭐ Features of Python Easy to learn and understand Simple and readable syntax Interpreted language Platform independent Large standard l...

what is Python Date and Time ? Complete Guide with Examples:

  ✍️ Introduction Python provides powerful tools to work with dates and times . The most commonly used module is datetime . The datetime module allows Python programs to create, manipulate, format, and perform calculations with dates and times easily. Date and time handling is used in: Logging systems Attendance & billing systems Data analysis Real-time applications How To Import Date and Time Module : In Python, the datetime module is used to work with dates , times , and date–time combinations . It is part of Python’s standard library, so no installation is required. You can import it in different ways depending on your need. import datetime Get Current Date and Time: This code obtains the current system date and time as a single datetime object using the datetime module. Example: import datetime now = datetime.datetime.now() print (now) Output: 2026-02-13 11:25:53.445827 "Code executed successfully"  Get Only Date: This code retrieves t...

Features of Python Programming Language Explained with Examples

✍️ Introduction Python is one of the most popular programming languages because of its powerful and easy-to-use features. It is designed to make programming simple, readable, and efficient. Python is widely used by beginners as well as professionals due to its flexibility and strong community support. In this article, we will discuss the main features of Python programming language in simple English with easy examples. 🧠 What Are Features of Python? Features of Python are the special characteristics that make it different from other programming languages. These features help programmers write clean, readable, and efficient code with less effort. ⭐ Key Features of Python Programming Language 1️⃣ Easy to Learn and Easy to Use Python has a simple syntax that is close to the English language. This makes it very easy for beginners to learn and understand programming concepts. Example: print("Hello, World!") 2️⃣ Interpreted Language Python is an interpreted language, which me...

Python Operators: Types with Examples

 ✍️Introduction In Python, operators are symbols used to perform operations on variables and values. Operators help us do calculations, comparisons, and logical decisions in programs. In this article, you will learn: • What Python operators are • Types of Python operators • Simple examples for each type