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

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

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

3.2.4 抛出异常

大多数面向对象的语言提供了名为exception(异常)的功能。通常来讲异常是系统内发生的突发事件。Exception提供了一种方式来检测问题然后进行处理。在Java、C#、C++、Swift和Visual Basic中,异常是通过关键字catch和throw来处理的。这有点像棒球游戏,但这里的关键概念是用特定的代码块用来处理特定的异常。这既解决了尝试找出错误发生的地方的问题,也解决了在正确的地方处理该错误的问题。

以下是Java中try/catch代码块的结构:

如果在try代码块中抛出了异常,catch代码块会处理该异常。如果代码块执行过程中抛出了异常,会发生以下事情:

1.try代码块会结束执行。

2.catch从句会检查对应的catch代码块能否处理这种异常(一个try代码块可能会对应多个catch从句)。

3.如果所有catch代码块都不能处理抛出的异常,那么该异常会传递给最近的更高一层的try代码块中(如果代码中没有捕获该异常,系统最终会捕获它,结果是无法预料的,可能导致应用程序崩溃)。

4.如果有一个catch从句匹配上了(遇到了第一个匹配的从句),会执行catch从句中的语句。

5.程序会从紧挨着try代码块的下面的语句处恢复执行。

以上几点足够说明异常处理是面向对象程序语言中的一个重要优势。以下是Java中处理异常的一个示例:

异常粒度

你可以在不同层级的粒度上捕获异常。你可以捕获所有的异常或者检查特定的异常(比如算术异常)。如果代码没有捕获异常,Java运行时会捕获它,那么Java运行时可能会崩溃! ...

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

桑德.范.乌格特
Java并发编程实战

Java并发编程实战

Brian Goetz, Tim Peierls

Publisher Resources

ISBN: 9787111684527