Skip to Content
面向对象的思考过程(原书第5版)
book

面向对象的思考过程(原书第5版)

by 马特 魏斯费尔德
August 2021
Intermediate to advanced
450 pages
4h 46m
Chinese
Pearson
Content preview from 面向对象的思考过程(原书第5版)

3.2.3 检查问题并试图恢复

检查潜在问题,捕获错误,并试图恢复的方案远胜于简单地检查问题并中止程序的方案。在这种情况下,通过代码检测发现问题,然后应用程序自身会尝试修复它。这在某些场景下是适用的。例如,请看以下代码:

显然如果代码中没有该条件语句,0会进入除法语句,因为不能除以0,从而导致系统异常。捕获该异常并设置变量为1,至少能保证系统不会崩溃。不过设置a为1可能不是一个正确的方案,因为结果是不正确的。更好的方案是提醒用户重新输入恰当的值。

混合错误处理技术

尽管事实上错误处理类型并不属于面向对象的核心范畴,但我认为在面向对象设计中可以考虑使用。抛出异常(接下来的小节会涉及)会带来昂贵的开销。因此,尽管异常是有效的设计决策,你也应该根据设计及性能要求,适当考虑其他错误处理技术(甚至使用tried-and-true结构化技术)。

尽管之前提到的错误检查技术强于什么都不做,但这种技术也有一些问题。比如并不总能在错误第一次发生的地方探测到。很可能问题发生一段时间后才会被探测到。不过详细解释异常处理已经超出了本书的范围。然而,在一开始设计类时就设计异常处理是非常重要的,而且通常操作系统自身也会对它发现的问题发出警告。

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

Node与Express开发(第2版)

Node与Express开发(第2版)

Ethan Brown
计算机科学导论:跨学科方法

计算机科学导论:跨学科方法

罗伯特 塞奇威克, 凯文 韦恩
手把手教会你linux

手把手教会你linux

桑德.范.乌格特
Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉

Publisher Resources

ISBN: 9787111684527