Else Block in Exception Handling in Python

Else Block in Exception Handling in Python

The else block in Python exception handling executes only if the try block completes successfully without any exceptions. It’s placed after all except blocks and before the finally block.

Basic Syntax:

python

try:
    # Code that might raise an exception
except SomeException:
    # Handle the exception
else:
    # Code that runs only if no exception occurred
finally:
    # Code that always runs (optional)

5 Basic Examples:

Example 1: Basic Division Operation

python

try:
    numerator = 10
    denominator = 2
    result = numerator / denominator
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
else:
    print(f"Division successful! Result: {result}")
# Output: Division successful! Result: 5.0

Example 2: File Operations

python

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("Error: File not found!")
else:
    print("File read successfully!")
    print(f"Content length: {len(content)} characters")
    file.close()

Example 3: List Index Access

python

my_list = [1, 2, 3, 4, 5]

try:
    value = my_list[2]
except IndexError:
    print("Error: Index out of range!")
else:
    print(f"Value at index 2: {value}")
# Output: Value at index 2: 3

Example 4: Dictionary Key Access

python

student = {"name": "Alice", "age": 20, "grade": "A"}

try:
    email = student["email"]
except KeyError:
    print("Error: Email key not found!")
else:
    print(f"Student email: {email}")
# Output: Error: Email key not found!

Example 5: Multiple Operations

python

try:
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))
    result = num1 + num2
except ValueError:
    print("Error: Please enter valid numbers!")
else:
    print(f"Sum: {result}")
finally:
    print("Operation completed.")

Key Points:

  • The else block runs only when no exceptions occur in the try block
  • It helps separate error-prone code from code that should only run if successful
  • Makes code more readable by clearly distinguishing normal flow from error handling
  • The else block executes before the finally block (if present)

When to use else:

  • When you have code that should only execute if the try block succeeds
  • To avoid catching exceptions that might be raised by the else block code
  • To make your intention clear that certain code depends on the success of the try block

Similar Posts

  • Demo And course Content

    What is Python? Python is a high-level, interpreted, and general-purpose programming language known for its simplicity and readability. It supports multiple programming paradigms, including: Python’s design philosophy emphasizes code readability (using indentation instead of braces) and developer productivity. History of Python Fun Fact: Python is named after Monty Python’s Flying Circus (a British comedy show), not the snake! 🐍🎭 Top Career Paths After Learning Core Python 🐍…

  • Polymorphism

    Polymorphism is a core concept in OOP that means “many forms” 🐍. In Python, it allows objects of different classes to be treated as objects of a common superclass. This means you can use a single function or method to work with different data types, as long as they implement a specific action. 🌀 Polymorphism…

  • Bank Account Class with Minimum Balance

    Challenge Summary: Bank Account Class with Minimum Balance Objective: Create a BankAccount class that automatically assigns account numbers and enforces a minimum balance rule. 1. Custom Exception Class python class MinimumBalanceError(Exception): “””Custom exception for minimum balance violation””” pass 2. BankAccount Class Requirements Properties: Methods: __init__(self, name, initial_balance) deposit(self, amount) withdraw(self, amount) show_details(self) 3. Key Rules: 4. Testing…

  • How to create Class

    🟥 Rectangle Properties Properties are the nouns that describe a rectangle. They are the characteristics that define a specific rectangle’s dimensions and position. Examples: 📐 Rectangle Methods Methods are the verbs that describe what a rectangle can do or what can be done to it. They are the actions that allow you to calculate information…

Leave a Reply

Your email address will not be published. Required fields are marked *