What I call the way to deal with errors is actually try:,except and raise .
First throws an instance,
Dictt={' A ': 1, ' B ': 2, ' C ': 3}try: if dictt[' d ']>1: #字典中没有 ' d ' print ("right!") Except Keyerror:print ("There is no ' d '")
The running result of the program:
There is no ' d '
Instead of raise, the result is:
Obviously, because the ' f ' does not exist, the if cannot be executed, causing the raise to execute
The difference between the two (Try:,except and raise):
The former, no matter what the conditions in the if, can be run, no error, and the latter, if the conditions to meet a certain standard, otherwise raise cannot run. Also, raise will interrupt the program, showing a red error, and the red hint is set in raise.
In a word, the use of raise is generally of practical significance. Typical usage: Defines a function that takes multiple arguments, one of which is the wrong type, and it is appropriate to use raise for error hints.
Example:
#实现两个整数的加法运算def Summ (ADD1,ADD2): if (Type (ADD1)) ==type (1) and (type (ADD2)) ==type (1): return (ADD1+ADD2) else: raise TypeError ("The parameters should be integers")
Comparison of two methods of handling errors in Python