Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

python - What's the difference between raise, try, and assert?

I have been learning Python for a while and the raise function and assert are (what I realised is that both of them crash the app, unlike try - except) really similar and I can't see a situation where you would use raise or assert over try.

So, what is the difference between raise, try, and assert?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The statement assert can be used for checking conditions at runtime, but is removed if optimizations are requested from Python. The extended form is:

assert condition, message

and is equivalent to:

if __debug__:
    if not condition:
        raise AssertionError(message)

where __debug__ is True is Python was not started with the option -O.

So the statement assert condition, message is similar to:

if not condition:
    raise AssertionError(message)

in that both raise an AssertionError. The difference is that assert condition, message can be removed from the executed bytecode by optimizations (when those are enabled--by default they are not applied in CPython). In contrast, raise AssertionError(message) will in all cases be executed.

Thus, if the code should under all circumstances check and raise an AssertionError if the check fails, then writing if not condition: raise AssertionError is necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...