Python异常处理

try/except语句

捕捉异常可以使用try/except语句。

try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。

如果你不想在异常发生时结束你的程序,只需在try里捕获它。

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:

触发异常

我们可以使用raise语句自己触发异常

raise语法格式如下:

raise [Exception [, args [, traceback]]]

语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。

最后一个参数是可选的(在实践中很少使用),如果存在,是跟踪异常对象。

断言(Assertation)

 The assert keyword is used when debugging code.

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

References:

  1. https://www.jianshu.com/p/24e6fb03d6d6
  2. Python 异常处理

  3. https://www.w3schools.com/python/python_try_except.asp

------------恢复内容结束------------

原文地址:https://www.cnblogs.com/dulun/p/14844391.html