β¨ Python
else Block in Exception Handling β Run Code Only When No Errors OccurIntroduction π
In Pythonβs exception-handling structure, the else block is used to run code **only when no exception occurs** inside the try block. This helps separate normal logic from error-handling logic.
Note
π‘ Think of
βIf everything went fine, run this.β
else as: βIf everything went fine, run this.β
1. Basic tryβexceptβelse Structure π§±
basic_else.py
try:
x = int("10")
except ValueError:
print("β Conversion error!")
else:
print("β Success! Converted number =", x)β else runs only when try has **no errors**.
2. Else + Finally π―
else_finally.py
try:
num = 10 / 2
except ZeroDivisionError:
print("β Cannot divide by zero!")
else:
print("β Division successful:", num)
finally:
print("π Done")Note
β
β
finally runs alwaysβ
else runs only when no exception occurs3. Why Use Else Block? π€
- β Keeps try block small and focused
- β Separates error-handling from normal logic
- β Makes code cleaner and easier to understand
- β Prevents catching exceptions accidentally inside success code
4. Example: Input Handling π€
input_else.py
try:
age = int(input("Enter age: "))
except ValueError:
print("β Please enter a valid number!")
else:
print("β You entered:", age)5. Example: File Reading π
file_else.py
try:
f = open("data.txt")
except FileNotFoundError:
print("β File not found!")
else:
content = f.read()
print("β File successfully read!")
print(content)
finally:
print("Closing program...")6. Example: Database Operation π
db_else.py
try:
print("Connecting to database...")
connected = True
except ConnectionError:
print("β Cannot connect!")
else:
print("β Connected successfully!")
# Perform DB operations7. Else Is NOT Executed If Any Exception Happens β
else_not_run.py
try:
x = 10 / 0
except ZeroDivisionError:
print("β Error occurred")
else:
print("β This will NOT run")8. Best Practice: Keep try Block Minimal π‘
try_minimal.py
# β Bad practice
try:
x = int(input())
y = x / 2
print("Result:", y)
except ValueError:
print("Invalid input!")β Better approach:
try_with_else.py
try:
x = int(input())
except ValueError:
print("Invalid input!")
else:
print("Result:", x / 2)9. Else Block in Loops π
else in loops runs only when the loop ends normally (without break). But here we focus on exception-handling else.
10. When to Use Else Block? π―
- β When success logic should run only if no errors occur
- β When try block handles risky code
- β When you want clear separation between βriskyβ and βsafeβ code
Conclusion π
>>βThe
else block makes your exception handling clean β letting you clearly separate success paths from error paths.β β¨You now fully understand the Else Block in Python! Want the next topic? Try Custom Exceptions, Raising Exceptions, Error Hierarchy, or File Handling. Just tell me! π