Python exception handling (Try ... Except)

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Copyright, without permission, is prohibited reprint


chapter


tryBlock so that you can detect errors in the code block.

exceptBlock so that you can handle the error.

finallyBlock so that you can execute the final code, regardless of trythe exceptoutcome of the block, finallycode block will be executed.

Exception Handling

When an error (or abnormal) occurs, Python will usually stop the execution and error.

These exceptions can use try/ exceptstatement processing:

Examples

The following tryblock exception is generated, because xthere is no definition:

try:
  print(x)
except:
  print("发生异常")

Because the tryblock error is raised, so the exceptblock will be executed.

If you do not tryblock, the program will crash and raise an error:

Examples

This statement generates an error because xthere is no definition:

print(x)

Except more

May define a plurality of except, for example, may be defined as a special error code blocks except a special:

Examples

This statement generates an error because xthere is no definition:

try:
  print(x)
except NameError:
  print("变量x没有定义")
except:
  print("其他错误")

else

Can use elsekeyword to define a code block, if no error occurs, elsethe code block is executed:

Examples

In this example, try block does not produce any error:

try:
  print("你好")
except:
  print("出错了")
else:
  print("一切正常")

finally

If you define a finallyblock, regardless of trywhether the block error is raised, it will execute finallythe block.

Examples

try:
  print(x)
except:
  print("出错了")
finally:
  print("'try except'处理结束")

This is useful for close objects, cleaning up resources:

Examples

Try not to write a document written:

try:
  f = open("test.txt")
  f.write("奇客谷教程")
except:
  print("写文件出错了")
finally:
  f.close() # 关闭文件

The file is closed.

Guess you like

Origin blog.csdn.net/weixin_43031412/article/details/94380426