Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 762
Defneit Avatar asked Oct 21 '16 18:10

Defneit


People also ask

What is the difference between raise and assert?

raise is used for raising an exception; assert is used for raising an exception if the given condition is False .

What does assert () do in Python?

The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.

What is the difference between assert and exception?

The key differences between exceptions and assertions are: Assertions are intended to be used solely as a means of detecting programming errors, aka bugs. By contrast, an exception can indicate other kinds of error or "exceptional" condition; e.g. invalid user input, missing files, heap full and so on.

What exception does assert raise?

The assert Statement If the expression is false, Python raises an AssertionError exception. If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.


2 Answers

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.

like image 194
Michal Krzyz Avatar answered Oct 06 '22 00:10

Michal Krzyz


Assert:

Used when you want to "stop" the script based on a certain condition and return something to help debug faster:

list_ = ["a","b","x"] assert "x" in list_, "x is not in the list" print("passed")  #>> prints passed  list_ = ["a","b","c"] assert "x" in list_, "x is not in the list" print("passed") #>>  Traceback (most recent call last):   File "python", line 2, in <module> AssertionError: x is not in the list 

Raise:

Two reasons where this is useful:

1/ To be used with try and except blocks. Raise an error of your choosing, could be custom like below and doesn't stop the script if you pass or continue the script; or can be predefined errors raise ValueError()

class Custom_error(BaseException):     pass  try:     print("hello")     raise Custom_error     print("world") except Custom_error:     print("found it not stopping now")  print("im outside")  >> hello >> found it not stopping now >> im outside 

Noticed it didn't stop? We can stop it using just exit(1) in the except block.

2/ Raise can also be used to re-raise the current error to pass it up the stack to see if something else can handle it.

except SomeError, e:      if not can_handle(e):           raise      someone_take_care_of_it(e) 

Try/Except blocks:

Does exactly what you think, tries something if an error comes up you catch it and deal with it however you like. No example since there's one above.

like image 28
MooingRawr Avatar answered Oct 06 '22 00:10

MooingRawr