Skip to Content
C++语言导学(原书第2版)
book

C++语言导学(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
5h 35m
Chinese
Pearson
Content preview from C++语言导学(原书第2版)

3.5.1 异常

让我们重新考虑Vector的例子。对2.3节中的向量,当我们试图访问某个越界的元素时,应该发生什么呢?

·Vector的编写者并不知道使用者在面临这种情况时希望如何处理(通常情况下,Vector的编写者甚至不知道向量被用在何种程序中)。

·Vector的使用者不能保证每次都检测到问题(如果他们能做到的话,越界访问也就不会发生了)。

假设越界访问是一种错误,我们希望能从中恢复,合理的解决方案是由Vector的实现者检测意图越界的访问并通知使用者,然后使用者可以采取适当的应对措施。例如,Vector::operator[]()能够检测到意图越界的访问,并抛出一个out_of_range异常:

throw将程序的控制权从某个直接或间接调用Vector::operator[]()的函数转移到out_of_range异常处理代码。为此,C++实现需能展开(unwind)函数调用栈以便返回调用者的上下文。换句话说,异常处理机制会退出一系列作用域和函数以便回到对处理这种异常表达出兴趣的某个调用者,一路上会按需要调用析构函数(参见4.2.2节)。例如:

如果希望处理某段代码的异常,应将其放在一个try块中。显然,对v[v.size()]的赋值操作将会出错。因此,程序进入到catch子句中,它提供了out_of_range类型错误的处理代码。out_of_range类型定义在标准库中(在<stdexcept>中),事实上,它也被一些标准库容器访问函数使用。 ...

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

软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu

Publisher Resources

ISBN: 9787111633280