6 min read
ā¢Question 12 of 41easyException Handling in Python
Handling errors with try-except.
What You'll Learn
- How exception handling works in Python
- try, except, else, finally blocks
- Catching specific vs general exceptions
- Raising and creating custom exceptions
- Best practices for error handling
Understanding Exceptions
Exceptions are errors that occur during program execution. Instead of crashing, Python allows you to catch and handle these errors gracefully using try-except blocks.
Common exceptions:
ValueError- Wrong value typeTypeError- Wrong operation for typeKeyError- Dict key not foundIndexError- List index out of rangeFileNotFoundError- File doesn't existZeroDivisionError- Division by zero
Basic Try-Except
code.pyPython
# Without handling - program crashes
# result = 10 / 0 # ZeroDivisionError!
# With handling - graceful error recovery
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
result = 0
print(f"Result: {result}") # Program continuesCatching Multiple Exceptions
code.pyPython
try:
num = int(input("Enter number: "))
result = 10 / num
except ValueError:
print("Please enter a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
# Catch multiple in one except
try:
# some code
pass
except (ValueError, TypeError) as e:
print(f"Value or Type error: {e}")
# Catch all exceptions (use sparingly)
try:
risky_operation()
except Exception as e:
print(f"An error occurred: {e}")The Full Try Block
code.pyPython
try:
file = open("data.txt", "r")
data = file.read()
number = int(data)
except FileNotFoundError:
print("File not found!")
number = 0
except ValueError:
print("File doesn't contain a valid number!")
number = 0
else:
# Runs ONLY if no exception occurred
print("File read successfully!")
finally:
# ALWAYS runs, even if exception occurred
print("Cleanup: closing file if open")
try:
file.close()
except:
passWhen Each Block Runs
| Block | When it runs |
|---|---|
try | Always (main code) |
except | Only when matching exception occurs |
else | Only when NO exception in try |
finally | ALWAYS (cleanup code) |
Raising Exceptions
code.pyPython
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return age
# Catching raised exceptions
try:
age = validate_age(-5)
except ValueError as e:
print(f"Invalid age: {e}")
# Re-raising exceptions
try:
validate_age(-5)
except ValueError:
print("Logging error...")
raise # Re-raise the same exceptionCustom Exceptions
code.pyPython
# Define custom exception
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
message = f"Cannot withdraw {amount}. Balance: {balance}"
super().__init__(message)
# Use custom exception
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(self.balance, amount)
self.balance -= amount
return amount
# Handle custom exception
account = BankAccount(100)
try:
account.withdraw(150)
except InsufficientFundsError as e:
print(f"Error: {e}")
print(f"Available: {e.balance}")Best Practices
code.pyPython
# BAD: Catching all exceptions silently
try:
risky_code()
except:
pass # Hides all errors!
# GOOD: Catch specific exceptions
try:
risky_code()
except SpecificError as e:
logger.error(f"Expected error: {e}")
handle_error()
# GOOD: Use context managers instead of try-finally
# Instead of:
try:
f = open("file.txt")
data = f.read()
finally:
f.close()
# Use:
with open("file.txt") as f:
data = f.read()
# GOOD: Check before acting (when possible)
# Instead of:
try:
value = my_dict[key]
except KeyError:
value = default
# Use:
value = my_dict.get(key, default)Interview Tip
When asked about Python exception handling:
- try-except catches errors, prevents crashes
- finally always runs (cleanup code)
- else runs only if no exception occurred
- Catch specific exceptions, not bare
except: - raise to throw exceptions, create custom ones
- Use context managers (with) when possible