Skip to Content
程序员的38堂成长课
book

程序员的38堂成长课

by Pete Goodliffe
January 2022
Beginner to intermediate
314 pages
6h 55m
Chinese
Posts & Telecom Press
Content preview from 程序员的38堂成长课
58
8
要诀
不要忽略代码中的任何错误。不要推迟到以后出错再处理,“以后”
处理通常表示不会处理。
8.1
 错误机制
我们的程序在很多情况下会以如下几种方式报错。
返回值
函数会有返回值,其中一些意味着“函数没有正常工作”。我们特别容易忽略返回值报
错,因为错误并不明显。实际上,忽略一些标准的
C
函数返回值已经成为实践中的标
准做法。你检查过
printf
函数的返回值吗?
返回值可能是最常见的错误报告通道:我们可以看到
函数
返回值;操作系统会
处理
系统
调用的返回值;在一些系统中,
线程
也可以有返回值。
返回值通常是一个整数值。在正常情况下,零值表示成功,而非零值表示一个错误代
码。在现代代码中,这是一个相当奇怪的惯用法。我们可以编写更具表现力的代码,比
如通过返回一个
Tuple
Optional
”类型,来同时返回操作是否成功和某种类型的
返回值(例如,
C++
中的
boost::optional
类型或
C#
中的
Nullable<T>
)。函数式编程
语言可能会通过函数的返回
类型
而不是一个特殊约定的值来指示错误。
Haskell
提供了
Maybe
类,
Scala
提供了
Option
Either
副作用
1
副作用的典型代表
errno
C
语言的一个怪异用法:一个单独的全局变量,用于表示错
误。它很容易被忽略且难以使用,并会导致各种棘手的问题。例如,当多个线程调用同
一个函数时会发生什么?
你可能会看到用于表明出错信息的其他通道或副作用。例如,你必须调用另一个函数来
检查操作是否“成功”。或者当出现错误时,对象会进入“无效”状态。 ...
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

管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python应用开发指南

Python应用开发指南

Posts & Telecom Press, Ninad Sathaye
解密金融数据

解密金融数据

Justin Pauley

Publisher Resources

ISBN: 9787115577948