Basic Try...Except Block
Mon 10 August 2026
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Cannot divide by zero
Score: 10
Category: chapter6_exception_handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Cannot divide by zero
Score: 10
Category: chapter6_exception_handling
try:
number = int("abc")
except ValueError:
print("Invalid number format")
Score: 5
Category: chapter6_exception_handling
Read Moretry:
risky_operation()
except Exception as e:
print("Error occurred:", e)
Error occurred: name 'risky_operation' is not defined
Score: 10
Category: chapter6_exception_handling
Read Moretry:
risky_operation()
except Exception as e:
print("Error:", e)
Error: name 'risky_operation' is not defined
Score: 10
Category: chapter6_exception_handling
Read Moretry:
value = int("abc")
except ValueError:
print("Invalid conversion")
except ZeroDivisionError:
print("Division error")
Invalid conversion
Score: 10
Category: chapter6_exception_handling
Read Moretry:
value = int("10")
result = value / 0
except ValueError:
print("Conversion error")
except ZeroDivisionError:
print("Division error")
Division error
Score: 10
Category: chapter6_exception_handling
Read Moretry:
try:
x = int("abc")
except ValueError:
print("Inner exception handled")
except Exception:
print("Outer exception handler")
Inner exception handled
Score: 10
Category: chapter6_exception_handling
Read Moredef safe_divide(a, b):
try:
return a / b
except ZeroDivisionError as e:
return f"Error: {e}"
except Exception as e:
return f"Unexpected error: {e}"
finally:
print("Operation attempted")
print(safe_divide(10, 0))
Operation attempted
Error: division by zero
Score: 10
Category: chapter6_exception_handling
Read Moretry:
result = 10 / 0
except ZeroDivisionError:
print("Handled division by zero safely")
Handled division by zero safely
Score: 10
Category: chapter6_exception_handling
Read Moretry:
value = int("xyz")
except ValueError:
print("Logging error before re-raising")
raise
Logging error before re-raising
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[1], line 2
1 try:
----> 2 value = int("xyz")
3 except ValueError:
4 print("Logging error before re-raising")
ValueError: invalid literal for int() with base …Category: chapter6_exception_handling
Read More