【Exception Handling】try... except... else... finally... + raise

355 阅读1分钟

Exception Handling 异常处理

exception - error

异常 - 错误

try... except...

try:

test a block of code for errors.

测试代码块中的错误。

except:

handle the error.

处理错误。

How they work

If try block raises an error, except block will be executed.

如果 try 块引发错误,则执行 except 块。

Example

try:
  print(x) # x is not defined
except:
  print("An exception occurred")

Multiple exceptions - 3 examples

Name error

# Print one message if the try block raises a NameError and another for other errors
try:
    print(x) # name error
except NameError:
    print("Variable x is not defined")
except:
    print("Something else went wrong")

output: Variable x is not defined

Other errors

try:
    x = 'a'
    x = x + 1 # other error
except NameError:
    print("Variable x is not defined")
except:
    print("Something else went wrong")

Output: Something else went wrong

Sequence

try:
    print(x) # name error
    x = 'a'
    x = x + 1 # other error
except NameError:
    print("Variable x is not defined")
except:
    print("Something else went wrong")

Output: Variable x is not defined

execute the code triggered by the first exception.

执行由第一个异常触发的代码。

Else

How it works

else executed this code if no errors were raised.

else 如果没有引起错误,则执行此代码.

Example

try:
  print("Hello.") # the try block does not generate any error
except:
  print("Something went wrong.")
else:
  print("Nothing went wrong.")

Outout: Hello. Nothing went wrong.

Finally

finally: execute code regardless if the try block raises an error or not.

无论 try 块是否引发错误,都执行代码。

Example

try:
  print(x)
except:
  print("Something went wrong.")
finally:
  print("The 'try except' is finished.")

Output: Something went wrong. The 'try except' is finished.

Raise an exception

raise throws(raises) an exception.

raise + type of error/Exception ("text to print")

Example

# Raise a TypeError if x is not an integer:
x = "hello"

if not type(x) is int:
    raise TypeError("Only integers are allowed")

Output:

Traceback (most recent call last):
  File "demo_ref_keyword_raise2.py", line 4, in <module>
    raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed

References

Python 异常处理 - 菜鸟教程

Python Try Except - w3schools

Relative Information

use 'while True' to put it in a loop

'continue' means to repeat the loop

'break' means to exit the loop