I use the following function to do extremely quick-and-dirty exception handling in an expression, without having to use try/except.
Python, 12 lines
1 2 3 4 5 6 7 8 9 10 11 12
def throws(f, *a, **k): "Return True if f(*a,**k) raises an exception." try: f(*a,**k) except: return True else: return False # Example - get numbers from a file, ignoring ill-formatted ones. data = [float(line) for line in open(some_file) if not throws(float, line)]
Maybe "raises" would be a better name, but I use "throws" - too much C++ rattling around in my brain I guess.
extremely quick-and-dirty. Indeed quick and dirty ;-)
Slight improvement. Just slightly less dirty:
You can then use
To catch the exceptions you anticipate, while passing along those that you _should_ avoid (such as SystemExit). If you want a very broad exception class, use
, which should cover all exceptions.