Skip to Content
Python实用技能学习指南
book

Python实用技能学习指南

by Posts & Telecom Press, Robert Smallshire, Austin Bingham
February 2024
Intermediate to advanced
316 pages
3h 47m
Chinese
Packt Publishing
Content preview from Python实用技能学习指南

第6章 异常

异常处理是一种停止“正常”程序流程并从周围的上下文或代码块处继续进行的机制。

中断正常流程的行为被称为“抛出(raising)”异常。在某些封闭的上下文中,必须处理抛出的异常,这意味着控制流被传递到异常处理程序中。如果异常将调用堆栈向上传播到程序的起始处,那么未处理的异常将会导致程序终止。一个异常对象主要包含异常事件发生的位置和原因等有关信息,该对象被传送到异常处理程序,以便处理程序可以询问异常对象并采取适当的操作。

如果你在其他流行的命令式语言(如C++或Java)中见到过异常,那么你已经了解了异常在Python中的工作原理。

对于“异常事件”的构成,人们已经进行了漫长而令人厌倦的辩论,其核心问题是,异常实际上是一个程度问题(有些事件比其他事件异常)。这种论点是有问题的,因为编程语言强加了一个错误的二分法,坚持认为一个事件是完全异常的,或者根本不是异常的。

在使用异常时,Python哲学处于自由主义的极端。异常在Python中是普遍存在的,了解如何处理它们至关重要。

由于异常是控制流程的一种手段,因此在REPL中演示异常会显得很笨拙,因此,在本章中,我们将使用一个Python模块来组织代码。从一个非常简单的模块开始,我们将使用该模块来探索这些重要的概念和行为。

将这些代码放到一个名为exceptional.py的模块中:

"""用于演示异常的模块。"""

def convert(s):
     """转换成一个整数。"""
     x = int(s)
     return x

将该模块中的convert()函数导入到Python的REPL中:

$ python3 Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

人工智能技术与大数据

人工智能技术与大数据

Posts & Telecom Press, Anand Deshpande, Manish Kumar
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835889626