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

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

  • non-capturing group, Named Groups,groupdict()

    To create a non-capturing group in Python’s re module, you use the syntax (?:…). This groups a part of a regular expression together without creating a backreference for that group. A capturing group (…) saves the matched text. You can then access this captured text using methods like group(1), group(2), etc. A non-capturing group (?:…)…

  • The Fractions module

    The Fractions module in Python is a built-in module that provides support for rational number arithmetic. It allows you to work with fractions (like 1/2, 3/4, etc.) exactly, without the precision issues that can occur with floating-point numbers. What Problems Does It Solve? Problem with Floating-Point Numbers: python # Floating-point precision issue print(0.1 + 0.2) # Output:…

  • Closure Functions in Python

    Closure Functions in Python A closure is a function that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope. Simple Example python def outer_function(x): # This is the enclosing scope def inner_function(y): # inner_function can access ‘x’ from outer_function’s scope return x + y return inner_function…

  • String Validation Methods

    Complete List of Python String Validation Methods Python provides several built-in string methods to check if a string meets certain criteria. These methods return True or False and are useful for input validation, data cleaning, and text processing. 1. Case Checking Methods Method Description Example isupper() Checks if all characters are uppercase “HELLO”.isupper() → True islower() Checks if all…

  • Python Functions

    A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Defining a Function In Python, a function is defined using the def keyword, followed by the function name, a set of parentheses (),…

Leave a Reply

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