try / except / finally
Exception handling lets you gracefully handle errors instead of crashing. Use try/except to catch errors, else for success, and finally for cleanup.
20 min•By Priygop Team•Updated 2026
Exception Handling
Exception Handling
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple except blocks
def safe_convert(value):
try:
return int(value)
except ValueError:
print(f"'{value}' is not a valid number")
return None
except TypeError:
print(f"Wrong type: {type(value)}")
return None
print(safe_convert("42")) # 42
print(safe_convert("hello")) # None
print(safe_convert(None)) # None
# try/except/else/finally
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero!")
return None
except TypeError as e:
print(f"Error: {e}")
return None
else:
print(f"Success: {a}/{b} = {result}")
return result
finally:
print("(Cleanup done)")
divide(10, 3)
divide(10, 0)
divide("a", 2)
# Getting error details
try:
numbers = [1, 2, 3]
print(numbers[10])
except IndexError as e:
print(f"Error: {e}")
print(f"Type: {type(e).__name__}")Tip
Tip
Catch specific exceptions, not bare except:. except ValueError: is much better than except: which catches everything including KeyboardInterrupt.
Diagram
Loading diagram…
Catch specific exceptions. Use else for success logic. finally for cleanup. Custom exceptions for your domain.
Common Mistake
Warning
Using bare except: catches SystemExit and KeyboardInterrupt, making your program hard to stop. Always specify the exception type.
Practice Task
Note
(1) Handle ValueError for invalid input. (2) Handle FileNotFoundError. (3) Use try/except/else/finally together.