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

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

  • Python timedelta Explained

    Python timedelta Explained timedelta is a class in Python’s datetime module that represents a duration – the difference between two dates or times. It’s incredibly useful for date and time arithmetic. Importing timedelta python from datetime import timedelta, datetime, date Basic Syntax python timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Examples 1. Basic timedelta Creation python from datetime…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

  • List of Basic Regular Expression Patterns in Python

    Complete List of Basic Regular Expression Patterns in Python Character Classes Pattern Description Example [abc] Matches any one of the characters a, b, or c [aeiou] matches any vowel [^abc] Matches any character except a, b, or c [^0-9] matches non-digits [a-z] Matches any character in range a to z [a-z] matches lowercase letters [A-Z] Matches any character in range…

  • What is Python library Complete List of Python Libraries

    In Python, a library is a collection of pre-written code that you can use in your programs. Think of it like a toolbox full of specialized tools. Instead of building every tool from scratch, you can use the tools (functions, classes, modules) provided by a library to accomplish tasks more efficiently.   Here’s a breakdown…

Leave a Reply

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