0

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.

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

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.

1 Comment

I agree. Not that i've ever encountered such a method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.