Python学习笔记(三十二)- 异常基础( Exception Basics)

1.说出异常处理(exception processing)有用的三件事。
答:异常处理对于错误处理(error handling),终止操作(termination actions)和事件通知(event notification)很有用。它还可以简化特殊情况的处理,并可用于实现替代控制流(control flow)作为一种结构化的“go to”操作。通常,异常处理还会减少程序可能需要的错误检查代码量 - 因为所有错误都会过滤到处理程序,您可能不需要测试每个操作的结果。

2.如果你不做什么特别的事情来处理,那么异常会发生什么呢?
答:任何未捕获的异常最终都会过滤到Python在程序顶部提供的默认异常处理程序。此处理程序打印熟悉的错误消息并关闭您的程序。

3.你的脚本如何从异常中恢复?
答:如果您不想默认错误消息并关闭,则可以编写try / except语句来捕获并从其嵌套代码块中引发的异常中恢复。捕获异常后,异常终止,并在尝试后继续执行程序。

4.说出两种在脚本中触发异常的方法。
答:raise和assert语句可用于触发异常,就像Python本身引发的一样。原则上,你也可以通过编程错误来引发异常,但这通常不是一个明确的目标!

5.说出两种方式来指定在终止时间(termination time)运行的操作,无论是否发生了异常。
答:try / finally语句可用于确保在代码块退出后运行操作,无论该块是否引发异常。 with / as语句也可用于确保运行终止操作,但仅在处理支持它的对象类型时使用。

异常处理:

1.try/except: 从Python或你中所引发的异常中捕捉和恢复

2.try/finally: 无论是否发生异常,执行清理操作

3.raise: 手动在你的代码中引发异常

4.assert: 有条件地在你的代码中引发异常

5.with/as: 实现上下文管理器

注:转载《Learning Python 5th Edition》[奥莱理]

1. Name three things that exception processing is good for.
2. What happens to an exception if you don't do anything special to handle it?
3. How can your script recover from an exception?
4. Name two ways to trigger exceptions in your script.
5. Name two ways to specify actions to be run at termination time, whether an exception occurs or not.

1. Exception processing is useful for error handling, termination actions, and event notification. It can also simplify the handling of special cases and can be used to implement alternative control flows as a sort of structured “go to” operation. In general, exception processing also cuts down on the amount of error-checking code your program may require—because all errors filter up to handlers, you may not need to test the outcome of every operation.
2. Any uncaught exception eventually filters up to the default exception handler Python provides at the top of your program. This handler prints the familiar error message and shuts down your program.
3. If you don't want the default message and shutdown, you can code try/except statements to catch and recover from exceptions that are raised within its nested code block. Once an exception is caught, the exception is terminated and your program continues after the try.
4. The raise and assert statements can be used to trigger an exception, exactly as if it had been raised by Python itself. In principle, you can also raise an exception by making a programming mistake, but that's not usually an explicit goal!
5. The try/finally statement can be used to ensure actions are run after a block of code exits, regardless of whether the block raises an exception or not. The with/as statement can also be used to ensure termination actions are run, but only when processing object types that support it.

猜你喜欢

转载自blog.csdn.net/Enderman_xiaohei/article/details/88656873