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

  • group() and groups()

    Python re group() and groups() Methods Explained The group() and groups() methods are used with match objects to extract captured groups from regex patterns. They work on the result of re.search(), re.match(), or re.finditer(). group() Method groups() Method Example 1: Basic Group Extraction python import retext = “John Doe, age 30, email: john.doe@email.com”# Pattern with multiple capture groupspattern = r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’///The Pattern: r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’Breakdown by Capture…

  • Unlock the Power of Python: What is Python, History, Uses, & 7 Amazing Applications

    What is Python and History of python, different sectors python used Python is one of the most popular programming languages worldwide, known for its versatility and beginner-friendliness . From web development to data science and machine learning, Python has become an indispensable tool for developers and tech professionals across various industries . This blog post…

  • Date/Time Objects

    Creating and Manipulating Date/Time Objects in Python 1. Creating Date and Time Objects Creating Date Objects python from datetime import date, time, datetime # Create date objects date1 = date(2023, 12, 25) # Christmas 2023 date2 = date(2024, 1, 1) # New Year 2024 date3 = date(2023, 6, 15) # Random date print(“Date Objects:”) print(f”Christmas:…

  • Method overriding

    Method overriding is a key feature of object-oriented programming (OOP) and inheritance. It allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class). When a method is called on an object of the child class, the child’s version of the method is…

  • Dot (.) ,Caret (^),Dollar Sign ($), Asterisk (*) ,Plus Sign (+) Metacharacters

    The Dot (.) Metacharacter in Simple Terms Think of the dot . as a wildcard that can stand in for any single character. It’s like a placeholder that matches whatever character is in that position. What the Dot Does: Example 1: Finding Words with a Pattern python import re # Let’s find all 3-letter words that end with “at” text…

Leave a Reply

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