Skip to content

TP0301

Warning: warning: broad except clause discards the exception

  • this clause catches every exception and discards it, with help catch a specific class, re-raise with 'raise', or bind it with 'as e' and use it (M16)

From the golden case tests/cases/m16/tp0301_broad.tpn:

tp0301_broad.tpn
# A broad except clause that discards the exception is warning TP0301 (SPEC §3.10).
def risky(n: int) -> int:
return [1, 2][n]
try:
print(risky(5))
except:
pass
try:
print(risky(5))
except Exception:
print("something failed")
try:
print(risky(5))
except (KeyError, Exception):
print("something failed")
try:
print(risky(5))
except Exception as e:
print("unused binding")
# Deliberate handling: logging the exception, re-raising, or catching a specific class.
try:
print(risky(5))
except Exception as e:
print("failed:", e)
try:
try:
print(risky(5))
except:
print("cleaning up")
raise
except IndexError:
print("index")
try:
print(risky(5))
except IndexError:
pass
def handler(f: Callable[[], None]):
try:
f()
except Exception:
def later():
raise KeyError("not a re-raise of this clause")
later()

The compiler reports:

tp0301_broad.tpn:7:1: warning TP0301: this clause catches every exception and discards it
help: catch a specific class, re-raise with 'raise', or bind it with 'as e' and use it
tp0301_broad.tpn:12:1: warning TP0301: this clause catches every exception and discards it
help: catch a specific class, re-raise with 'raise', or bind it with 'as e' and use it
tp0301_broad.tpn:17:1: warning TP0301: this clause catches every exception and discards it
help: catch a specific class, re-raise with 'raise', or bind it with 'as e' and use it
tp0301_broad.tpn:22:1: warning TP0301: this clause catches every exception and discards it
help: catch a specific class, re-raise with 'raise', or bind it with 'as e' and use it
tp0301_broad.tpn:48:5: warning TP0301: this clause catches every exception and discards it
help: catch a specific class, re-raise with 'raise', or bind it with 'as e' and use it

The specification lists every code.