Concept
Catching Specific Exceptions
Never use a bare `except:`. Always name the exact error you anticipate: `except ValueError:`. This prevents swallowing critical bugs.
python
try:
num = int("cat")
except ValueError:
print("Caught bad number conversion!")
except ZeroDivisionError:
print("Caught division by zero!")
# 110. Catching Specific Exceptions Never use a bare `except:`. Always name the exact error you anticipate: `except ValueError:`. This prevents swallowing critical bugs: ```python try: num = int("cat") except ValueError: print("Caught bad number conversion!") except ZeroDivisionError: print("Caught division by zero!") ``` A bare `except:` is an anti-pattern. If you accidentally misspell a variable name inside the `try` block, bare `except` will swallow the `NameError`, leaving you debugging phantom errors for hours.
Checkpoint
Why is a bare `except:` considered dangerous in production code?
Practice
Safely divide `10` by `0` in a `try` block, catching strictly `ZeroDivisionError`. Print `"Cannot divide by zero"`.
01
Tap code blocks below to assemble
Available Blocks