The difference between trying to raise and approving

I have been learning Python for a while and raise functions and assert that (what I realized is that both of them crashing the application, as opposed to trying - except) are really similar, and I cannot see the situation in which you will use raise or assert , over try

So what is the difference between Raise, Try and Assert?

+22
source share
8 answers

Statement:

Used when you want to “stop” a script based on a specific condition and return something to speed up debugging:

 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 are helpful for this:

1 / Used with try and except parameters. Raise the error of your choice, you can configure it as below and not stop the script if you pass or contiune script; or errors raise ValueError() may be predefined

 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 that this did not stop? We can stop it using only output (1) in the exclusive block.

2 / Raise can also be used to reprocess the current error, to pass its 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 / exclude blocks:

does exactly what you think, something tries, if an error occurs, you will catch it and deal with it as you like. There is no example, as there is higher.

+28
source
 assert cond, "text" 

expands to a value

 if cond == False: raise AssertionError("text") 

use assert because it is more readable.

+27
source

raise - raise an exception.

assert - throw an exception if this condition (or does not match) is true.

try - execute code that may throw an exception, and if so, understand it.

+18
source
Blocks

try/except allows you to catch and manage exceptions. Exceptions can be raise , raise , and a lot of errors, such as trying to index an empty list. raise usually used when you find an error condition. assert similar, but an exception occurs only if the condition is met.

raise and assert have a different philosophy. There are many “normal” errors in the code that you detect and cause errors. The website may not exist or the parameter value is out of range.

Statements are usually reserved for “I swear this cannot happen” cases that seem to happen anyway. This is more like debugging runtime than normal runtime error detection. Claims can be disabled if you use the -O flag or run from .pyo files instead of .pyc files, so they should not be part of regular error detection.

If the product quality code throws an exception, then find out what you did wrong. If it raises an AssertionError , you have a big problem.

+10
source

Exceptions are what Python (and some other languages) use to eliminate errors that occur when executing code. raise ExceptionName says that there is an error in the code, and indicates what the problem is by throwing an exception related to this problem. assert expression evaluate expression and throw an exception if it is false.

try used to execute code that may throw an exception that you expect. Instead of stopping the program, you can catch the exception and handle it in your code.

Example: say you have a dictionary and a list. You want to search for things from the list in the dictionary until you reach what is not in the dictionary:

 try: for item in my_list: print(my_dictionary[item]) except KeyError as e: #KeyError is the Exception raised when a key is not in a dictionary print('There is no {} in the dictionary'.format(e.args[0])) 
+1
source

An assertion is usually used when testing code to make sure something works:

 def test_bool(): assert True != False 

Where as a try, raise and exclude makeup exception handling, which is the preferred way in python to handle and propagate errors.

Most libraries and python built-in modules will go up and throw an exception of one type or another if something goes wrong. Often in your own code, you also want to throw an exception if you find that something is wrong. Say, as an example, you are writing an email address validator, and you wanted to throw an exception if the address did not contain the @ sign. you might have something like this (this is a toy code, don't really check for such emails):

 def validate_email(address): if not "@" in address: raise ValueError("Email Addresses must contain @ sign") 

Then, in another place in your code, you can call the validate_email function, and if it finishes, an exception will be thrown.

 try: validate_email("Mynameisjoe.com") except ValueError as ex: print("We can do some special invalid input handling here, Like ask the user to retry the input") finally: close_my_connection() print("Finally always runs whether we succeed or not. Good for clean up like shutting things down.") 

It is important to know that when an exception occurs, it skips the call stack until it finds a handler. If he never finds a handler, he will abort the program with an exception and a stack trace.

One thing you don't want to do is something like:

 if __name__ == '__main__': try: print(1/0) except Exception as ex: pass 

Now you have no way to find out why your application exploded.

One thing you'll often see, and this is normal:

 import logging if __name__ == '__main__': try: print(1/0) except Exception as ex: logging.exception(ex) raise 

Raising in this case, since it has no parameters, repeatedly causes the same error. Often in the web code you will see something similar that does not restore the exception, because it will send an error to the client 500 and then continue the next request, so in this case you do not want the program to end.

+1
source

Statements

  • It should be used for debugging purposes only.
  • Although they are similar to Raise / Exclusions, they serve different purposes because they are useful for indicating scenarios in which a software error cannot be fixed from
  • Assertions always raise AssertionError exceptions, this is how they work:

syntax: assert_stmt ::= "assert" expression1 ["," expression2]

at runtime, this translates to:

 if __debug__: if not expression1: raise AssertionError(expression2) 
  • __debug__ is a built-in flag that usually has the value true, but if the optimization is started, it will be false, therefore the statements will have dead code => are disabled with the -O and -OO flags when Python starts (or env PYTHONOPTIMIZE variable) in CPython) therefore, do not rely on them for code logic.
  • Do not use statements to verify data due to the previous paragraph
  • A good use case for statements => causes the program to “explode” if some unexpected state of the program should stop it under any circumstances => in this way, in circumstances where an exception, if it is detected, will lead to the termination of the program in general.
  • If you have a program without errors, then statements should never be run, they serve as a test of the program’s performance
  • Be careful when using data structures (such as tuples) as expression1 in statements that are always evaluated as True for non-empty values ​​=>, statements will always fire when breaking a program - for example: assert (<some_test>, 'warn string') = > pay attention to the design of the tuple (wrong!)

Check: Catching fake Python claims Dan Bader's CI

Raise / Exceptions

  • Their goal is to process scripts when the program logic is in exceptional condition, but you know which logic to recover from this state
  • When you throw an exception, you can make the type of the exception correspond to the error (it is better to control the semantic value) and catch it later => so that you can create several types of exceptions that you know how to recover and handle them
  • They represent a mechanism for handling known / expected runtime error scenarios.
  • Useful for validating data when using if statements and raising exceptions to validate for each scenario.

Try

  • This is just a syntax element for coding exception handling

By the way, I highly recommend Dan Bader’s book "Python Tricks: The Book" (from realpython.com )

+1
source

There is no difference between assert and raise AssertionError , they will be compiled with the same bytecode:

 import dis def foo1(param): assert param, "fail" def foo2(param): if not param: raise AssertionError("fail") print(dis.dis(foo1)) print(dis.dis(foo2)) 

Output:

  4 0 LOAD_FAST 0 (param) 2 POP_JUMP_IF_TRUE 12 4 LOAD_GLOBAL 0 (AssertionError) 6 LOAD_CONST 1 ('fail') 8 CALL_FUNCTION 1 10 RAISE_VARARGS 1 >> 12 LOAD_CONST 0 (None) 14 RETURN_VALUE None 7 0 LOAD_FAST 0 (param) 2 POP_JUMP_IF_TRUE 12 8 4 LOAD_GLOBAL 0 (AssertionError) 6 LOAD_CONST 1 ('fail') 8 CALL_FUNCTION 1 10 RAISE_VARARGS 1 >> 12 LOAD_CONST 0 (None) 14 RETURN_VALUE None 
0
source

Source: https://habr.com/ru/post/1011564/


All Articles