I use the following function to do extremely quick-and-dirty exception handling in an expression, without having to use try/except.
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.