Python Design Patterns 简明教程

Python Design Patterns - Exception Handling

处理异常也是设计模式的一个主要标准。异常是在程序执行过程中发生的错误。当发生特定错误时,生成一个异常非常重要。这有助于减少程序崩溃。

Handling exceptions is also a primary criterion of design patterns. An exception is an error that happens during the execution of a program. When a particular error occurs, it is important to generate an exception. This helps in curbing program crashes.

Why use exceptions?

异常是处理程序中错误和特殊情况的便捷方式。当用户认为指定的代码可能产生错误时,使用异常处理非常重要。

Exceptions are convenient ways of handling errors and special conditions in a program. When a user thinks that the specified code can produce an error then it is important to use exception handling.

Example – Division by zero

import sys

randomList = ['a', 0, 2]

for entry in randomList:
   try:
      print("The entry is", entry)
      r = 1/int(entry)
      break
   except:
      print("Oops!",sys.exc_info()[0],"occured.")
      print("Next entry.")
      print()
print("The reciprocal of",entry,"is",r)

Output

上述程序生成以下输出 −

The above program generates the following output −

exceptions

Raising Exceptions

在 Python 编程中,特别是当运行时发生相应的代码错误时,会引发异常。这可以用 “raise” 关键字强制引发。

In Python programming specifically, exceptions are raised when corresponding error of code occurs at run time. This can be forcefully raised using the “raise” keyword.

Syntax

   raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt