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

  • Functions as Objects

    Functions as Objects and First-Class Functions in Python In Python, functions are first-class objects, which means they can be: 1. Functions as Objects In Python, everything is an object, including functions. When you define a function, you’re creating a function object. python def greet(name): return f”Hello, {name}!” # The function is an object with type ‘function’…

  • Global And Local Variables

    Global Variables In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a…

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • re.fullmatch() Method

    Python re.fullmatch() Method Explained The re.fullmatch() method checks if the entire string matches the regular expression pattern. It returns a match object if the whole string matches, or None if it doesn’t. Syntax python re.fullmatch(pattern, string, flags=0) import re # Target string string = “The Euro STOXX 600 index, which tracks all stock markets across Europe including the FTSE, fell by…

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

Leave a Reply

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