错误和异常

当出错时,你通常会看到Python的”异常”(exception)。Python甚至试图指出什么原因导致异常。你经常见到异常的名字, 如NameErrorValueError(参见Python参考手册py中的完整异常列表)。

  1. sage: 3_2
  2. ------------------------------------------------------------
  3. File "<console>", line 1
  4. ZZ(3)_2
  5. ^
  6. SyntaxError: invalid syntax
  7. sage: EllipticCurve([0,infinity])
  8. ------------------------------------------------------------
  9. Traceback (most recent call last):
  10. ...
  11. TypeError: Unable to coerce Infinity (<class 'sage...Infinity'>) to Rational

有时候交互的debugger对于检查错误非常有用。你可以使用%pdb打开或关闭它(默认是关闭的)。如果引发了一个异常,并且debugger是打开的,会出现提示符ipdb>。在debugger中,你可以输出任何局部变量的状态,检查栈的上下文。

  1. sage: %pdb
  2. Automatic pdb calling has been turned ON
  3. sage: EllipticCurve([1,infinity])
  4. ---------------------------------------------------------------------------
  5. <type 'exceptions.TypeError'> Traceback (most recent call last)
  6. ...
  7. ipdb>

在提示符ipdb>中输入?可以得到debugger的命令列表:

  1. ipdb> ?
  2. Documented commands (type help <topic>):
  3. ========================================
  4. EOF break commands debug h l pdef quit tbreak
  5. a bt condition disable help list pdoc r u
  6. alias c cont down ignore n pinfo return unalias
  7. args cl continue enable j next pp s up
  8. b clear d exit jump p q step w
  9. whatis where
  10. Miscellaneous help topics:
  11. ==========================
  12. exec pdb
  13. Undocumented commands:
  14. ======================
  15. retval rv

按Ctrl+D或输入quit返回Sage.