Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use the ‘except clause’ with No Exceptions in Python?
In Python, the except clause is used to handle exceptions that may occur inside a try block. When no exceptions are raised, the except block is simply skipped, and program execution continues normally.
Basic Exception Handling Flow
When code inside the try block executes without raising any exceptions, the except block is ignored, and the program continues to the next statement ?
try:
result = 10 / 2
print("Division successful:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Program continues...")
Division successful: 5.0 Program continues...
Using else Block for Success Cases
The else block executes only when no exception occurs in the try block. This separates normal execution from error-handling code ?
try:
value = int("123")
print("Conversion attempt completed")
except ValueError:
print("Invalid input - not a number")
else:
print("Conversion succeeded:", value)
print("Value type:", type(value))
Conversion attempt completed Conversion succeeded: 123 Value type: <class 'int'>
Using finally Block
The finally block runs regardless of whether an exception occurs. It's typically used for cleanup operations like closing files or releasing resources ?
try:
numbers = [1, 2, 3, 4, 5]
print("First element:", numbers[0])
print("List processing successful")
except IndexError:
print("List is empty or index out of range")
finally:
print("Cleanup: Operation completed")
print("Memory can be freed")
First element: 1 List processing successful Cleanup: Operation completed Memory can be freed
Complete Exception Handling Structure
Here's how try, except, else, and finally work together when no exception occurs ?
def safe_divide(a, b):
try:
result = a / b
print(f"Attempting division: {a} / {b}")
except ZeroDivisionError:
print("Error: Division by zero")
return None
except TypeError:
print("Error: Invalid data types")
return None
else:
print("Division completed successfully")
return result
finally:
print("Function execution finished")
# Test with valid inputs
answer = safe_divide(15, 3)
print("Result:", answer)
Attempting division: 15 / 3 Division completed successfully Function execution finished Result: 5.0
Best Practices
Always catch specific exceptions rather than using bare except clauses. This makes debugging easier and prevents catching unexpected errors ?
# Good practice - specific exceptions
try:
data = {"name": "Alice", "age": 25}
print("Name:", data["name"])
print("Age:", data["age"])
except KeyError as e:
print(f"Missing key: {e}")
except TypeError as e:
print(f"Type error: {e}")
else:
print("All data accessed successfully")
Name: Alice Age: 25 All data accessed successfully
Conclusion
When no exceptions occur, except blocks are skipped, else blocks execute, and finally blocks always run. Use specific exception types and the else clause to create clean, readable error-handling code.
