Reputation: 10056
I have the following code:
def causes_exception(lamb):
try:
lamb()
return False
except:
return True
I was wondering if it came already in any built-in library?
/YGA
Edit: Thx for all the commentary. It's actually impossible to detect whether code causes an exception without running it -- otherwise you could solve the halting problem (raise an exception if the program halts). I just wanted a syntactically clean way to filter a set of identifiers for those where the code didn't except.
Upvotes: 0
Views: 148
Reputation: 6044
There's assertRaises(exception, callable)
in unittest
module and this is probably the only place where such check makes sense.
In regular code you can never be 100% sure that causes_exception
you suggested are not causing any side effects.
Upvotes: 4
Reputation: 75805
No, as far as I know there is no such function in the standard library. How would it be useful? I mean, presumably you would use it like this:
if causes_exception(func):
# do something
else:
# do something else
But instead, you could just do
try:
func()
except SomeException:
# do something else
else:
# do something
Upvotes: 8
Reputation: 281695
I'm not aware of that function, or anything similar, in the Python standard library.
It's rather misleading - if I saw it used, I might think it told you without calling the function whether the function could raise an exception.
Upvotes: 2