Peter Cai

The Case Against Exceptions


Goto statements went out of style in the 60s, relegated today to be the prototypical example of bad coding. Yet hardly anyone seems to be bothered by exceptions, which do basically the same thing. Used improperly, exceptions behave like goto statements and can be just as bad.

Exceptions essentially allow you to move error handling code out to a dedicated location. They have the added benefit that they can propagate up the stack so you can consolidate error handling into sensible modules. This allows certain subsystems to not care about exceptions because they can be handled by a caller. Gotos on the other hand generally would require every function have its own error handling section, either because the language doesn’t support gotos to a different scope, or the fact that it would be a terrible idea even if it was supported.

As a corollary, without exceptions you end up having to check every method call to ensure it succeeded, whereas exceptions optimize for the common case and make for much cleaner looking code.

Unfortunately, these benefits are mostly illusory, if you aren’t careful. You end up needing to write much more exception handling code to handle the different cases, and it’s incredibly easy to introduce subtle and hard-to-spot bugs. For example, suppose you have the following (loosely based on a snippet by Raymond Chen):

try {
} catch (Exception e) {
    // error handling


class Package {
    void Install() {

Notice the subtle bug here: if CreateDatabase throws, then the catch statement needs to know that CopyFiles() and UpdatePermissions() have already been run, but we’ve already lost that important context because we returned from those functions already. To be correct, the catch clause needs to know exactly how the install method works, what it can throw, and in what order it performs its operations (in this case, a cleanup method needs to know that permissions should be reverted and copied files removed. And depending on how far CreateDatabase got, it may have to clean up database files as well). This introduces tight coupling that isn’t immediately obvious because in the common-case scenario, nothing goes wrong and the bug is not exposed. However, important information about where the exception originated is lost unless additional work is done to preserve this state.

More generally, exceptions can decrease code visibility, because it’s extremely hard to tell if code is correct by looking at it. Did you forget to catch possible exceptions here, or is it handled further up the stack? Does any given method document all the exceptions it could throw? How do you know without reading the declaration?

These problems are not academic and invariably many larger projects become basically unmanageable because each subsystem introduces another layer of exceptions that must be handled. This leads to what I call whack-a-mole debugging: just run the code in production, and every time an uncaught exception causes a crash/bug, you go in and find where you let the exception leak and plug the hole, then repeat this forever.

But wait! What about finally statements? Finally can help improve the atomicity of methods by cleaning up, freeing resources, and generally making state consistent again. But they are once again tightly coupled to exactly what the throwing method was doing: what needs to be cleaned up? What is the order of operations of the function that threw? More importantly, will this break if the function changes later down the line? The catch / finally blocks might not even be in the same file or class, which means the code locality is now far enough away that there is a brittle sort-of-contract here that’s probably fuzzily documented, if at all.

But wait! What about checked exceptions like in Java? Doesn’t that solve a problem by explicitly declaring what the caller should expect and handle?

Even assuming they are implemented and used correctly, checked exceptions suffer from a versioning problem. Changing what exceptions can be thrown in a method can cause calling code to break or stop compiling, so checked exceptions are actually part of a method’s signature. Want to add a new throws declaration in a library? You can’t — you have to make a wrapper method to ensure backwards compatibility, assuming other people use your code. So unless you are prepared to do this (or don’t care that other people depend on your code) you must never change the throws declaration of a method.

The alternative without checked exceptions is just as bad: a call to any random library could crash you at any moment because it threw an unchecked exception you weren’t expecting. All told, it makes it a total pain to reuse code because literally any function call is a hidden minefield of invisible gotos: can you guarantee the call won’t throw, and that everything it transitively depends on won’t throw either? No? Then you better wrap it in a massive try statement. Exceptions mean any method anywhere can return at any moment, creating exponentially more return paths for every line of code.

Another subtle problem exceptions can cause is it can force you to architect your code differently, due to disagreements on the meaning of an exception: you might throw exceptions rarely, but a library might be more liberal with them, which can force you to change how your code is structured to be more correct when using this library. Because partially-written states are a real threat when programming with exceptions, you may end up having to structure a lot of code into a “commit” phase where exceptions won’t cause problems.

Some Suggestions
1. Set and enforce rules on how and where exceptions can be thrown and where they will be expected and handled. Make a guarantee about the side effects of a function when it throws, and what the catch block will do in terms of cleanup.
1a. Avoid operating under uncertainty: don’t do anything fancy in a global catch-all block. Catch the most precise type of exception and do the least amount of work possible.

2. Create and enforce boundaries to encapsulate subsystems; do not allow exceptions to cross subsystem boundaries. This is the loose coupling pattern applied to exception handling. It will help prevent return paths from exploding exponentially.
2a. You can use a stricter version of this rule by requiring your own code to never throw. This way, you only have to worry about external libraries that might use exceptions, but you can abstract this away from other modules. Google’s own C++ style guide forbids throwing exceptions.

Why are Microsoft Products so Large?

A few months ago I anonymously answered a question on Quora, and it turned out to be my most popular answer ever, by several orders of magnitude. I’ve reposted it here, in order to expand on it a little bit.

Question (paraphrased): Why is Office more than 800MB in size, when LibreOffice can come preloaded with all of Ubuntu on a 750MB CD?

This question seems a little loaded, and is looking for an excuse to accuse Office of bloat. However, it’s important to keep in mind how difficult it is to make a software suite: you have an extremely broad user base, comprising the proverbial grandma who fires up Word to type up an email, to the banker who uses the most advanced pivot-table-sparkline-sprinkled features of Excel. Here’s a couple major reasons I can think of, in no particular order:

  • Office ships with a huge and growing number of templates, graphics, macros, default add-ons, help documents, etc. This is a major driver of bloat — it has nothing to do with lines of code, and everything to do with a vibrant, comprehensive, and growing ecosystem.
  • Office is decades old. Think about this for a moment. I’ve debugged code that was written in the early 90s. Since Office is pretty well designed and written (contrary to public perception), we almost never throw away old code. So the cumulative effects of years of new features tends to only grow the codebase. Properly leveraged, this is a major competitive advantage.
  • The sheer number of features in Office is mind-boggling. For most releases, Office closes more bugs (not sure if I’m allowed to disclose numbers) than most products have lines of code. Failure to understand how many features Office has is the #1 cause of death to direct competitors.
  • Office installs all code that it needs out of the box, with no external dependencies aside from the Windows API. This might seem counter-intuitive, but it actually makes the suite much larger. This is because we don’t rely on any third party library or framework. This can obscure the real size of installations such as LibreOffice, because it requires Java (and its default library), but nobody counts that against the size of LibreOffice’s installation. The same can be said of .NET applications – .NET itself is a massive codebase.
  • Licensing and code obfuscation plays a small factor. In addition to having to write licensing and antipiracy code that LibreOffice doesn’t need to implement, this must be obfuscated and protected against attacks. No easy feat, considering the attacker has local administrator rights. Also, Office is designed to be resistant to failure, and there is significant updating and security support built into the platform. This all adds weight.
  • Running in native code also means there are fewer abstractions; Office has code to deal with weird hardware and software configurations. It accounts for settings that stupid “registry cleaners” tweaked that would otherwise break it. It ships in 40+ languages. It knows how to deal with paths that exceed 255, or contain unicode characters. It contains security checks to defend against users opening malicious excel documents. There are hundreds more examples of things Office does that nobody realizes, but which would be sorely missed if they disappeared. This all takes code.

In general terms, Microsoft products optimize for the long tail of use cases. This means it has lots and lots of features that are seldom used. The 80/20 rule applies here: 80% of the users use 20% only of the features. There is a nuance to this rule though: every user uses a different 20% of the product. This means a software suite needs exponentially more features to capture a larger and larger share of the market; Office owns the market.

The reasons for Office’s dominance is poorly understood, and often attributed to format lock-in, or being the existing standard. But Office really wins by fully exploiting its economy-of-scale, and size is a side-effect of this. The massive user base allows Microsoft to invest in features that are relevant to only a small segment of users and still turn a positive ROI. But Microsoft often invests in features even when ROI is negative. Subsidizing unprofitable features means Microsoft can do lots and lots of things that competing software won’t do. This means competitors will have to burn money to catch up to Office, which they won’t have because they don’t have as large a customer base[1]. This essentially guarantees Office’s dominance.

It also explains why Office takes up so much space. It’s not a bug; it’s a feature.

[1] Except Google, which is apparently happy to subsidize from search.

Why do new computers have so much crapware?


tl;dr: because that’s what the market wants.

The commodity PC business is very competitive. The margin on a typical consumer desktop or laptop computer is at break-even or less. Mostly, profits come from selling support or extended warranties and the like.

Imagine you are a PC manufacturer. Due to intense pricing pressure, you are basically losing a couple dollars on every sale. Now imagine some software vendor comes along and offers you $10 per unit to preload Office, or some antivirus, or whatever. Would you rather:

  1. Say no, and continue to lose money on every sale.
  2. Say no, and raise prices to cover costs, but lose all sales to your competitor.
  3. Say yes, and preload the crapware to lower the cost-per-unit?

Hint: only one of these results in you staying in business.

How is any of this the fault of consumers? Because consumers will search online for five hours to save 7 bucks on an 600 dollar laptop. In this kind of environment, you either preload trialware, or your prices aren’t low enough to move any units.

The same kind of nonsense is also happening to the airline industry[1], which is why they are always inventing baggage fees and dreaming up ways to charge customers for using the restroom.


[1] To be fair, there are other causes, one of them being an entire industry designed to work when oil is < 80 dollars/barrel and go bankrupt when it isn’t.

People prefer Bing over Google when the labels are swapped

SurveyMonkey last month released some surprising insight from a study they recently did comparing users’ search preferences.

The result? It turns out people prefer Bing over Google, but only if you label them Google results. Actually, if you correct for the Google brand, people outright prefer Bing.


Why does this matter? Because it means Google’s search quality is actually inferior to Bing’s. If you look at the preference graphs, this is obvious because Google slightly edges out Bing when the labels are correct, but when the labels are swapped, Bing’s results shoot WAY ahead. However — there are a couple nuances we can’t get into here. For example, it’s not clear if Bing is universally better over the set of all queries, or if they managed the trivial task of optimizing the most common ones. Anecdotally, my experience is that Bing is fairly good at long tail queries, although I have sometimes had to switch to Google for very specific and obscure searches about narrow subjects. Unfortunately, nothing in SurveyMonkey’s blog post gives us any further clues on this.

This should be a major coup for Bing, but it’s not clear what they do with this information: after all, they’re still Bing. Basically, it’s not clear whether the problem is that they’re not Google, or that they’re Microsoft. I suspect it’s probably a mix of both: old habits die hard, and Google is good enough for most people. You’re not going to get an order of magnitude improvement in relevance like Google was over the old search engines. And even though search theoretically has very low lock-in, the incentives to switch are actually fairly low: marginally better results in exchange for changing a well-practiced workflow, and admitting that an iconic search engine is no longer the best. Never underestimate the human affection with rationalization.

In addition to many people instinctively having a grudge against Microsoft, they also have a fairly terrible marketing department. Remember, these are the guys who came up with the name “Windows Phone 7 Series” and insisted that was the official name. Also recall that Bing in some Chinese dialects sounds a bit like “disease” or “sickness.” That’s not exactly the kind of connotation you want with the world’s fastest growing internet population.

It’s interesting to note that SurveyMonkey was not commissioned by Microsoft to do this study; in fact, Google is an investor in SurveyMonkey.

Survey results here:

Hey Engineers, Let’s Stop Being Assholes?


There’s this toxic idea in tech circles right now that’s starting to get really tiring. And it pains me to have to point this out because I could just blissfully go along with it, and give myself that self-congratulatory pat on the back that most of the tech world is doing on a nearly daily basis.

It’s the elitism. There’s this culture (cultivated by engineers) that worships engineers and shuns everyone else for not ‘being technical.’ This culture is backwards and counterproductive. It presupposes that engineering is the only thing that matters, and that everything else must defer to it.

There’s a reasonable origin for this line of thinking. Back in the dot com days, business majors were raising 50 million to make online wedding invitations and going public because they had a homepage. MBAs were looking for some engineers to “code up this idea quick,” as if the tech part of a tech company was just this checkbox that needed filling. As if engineers were these interchangeable cogs in the machine of a startup. Of course, those tech companies imploded and for most of them, technology wasn’t the primary cause. But even really great business ideas often failed for lack of technical expertise. It turns out people who don’t know how to create software are also terrible at recognizing how important (and hard) it is.

But the reverse is also true. And that’s how far the pendulum has swung in the other direction. There are lots of engineers proudly proclaiming that everything that isn’t engineering is just some checkbox department filled with warm bodies who weren’t good enough to be programmers. As those in the know have known for a long time, it turns out things like business development and “having customers” is pretty important too. It turns out people who don’t specialize in a non-technical role are also terrible at realizing how hard and important it is.

Which brings me to the general observation that everyone thinks their job is obviously the most important and indispensable. Not surprisingly, everyone is wrong, but engineers have convinced themselves that because the MBAs were demonstrably wrong about engineering, engineering must be right. Which is just a logical fallacy wrapped in wishful thinking sprinkled with the chocolate covered bacon bits of all your friends who also happen to be engineers agreeing.

This false premise (engineering is everything) leads to all sorts of crazy conclusions. One of them is that everyone should learn to code. This is stupid, and a waste of time. There’s no substitute for computer literacy, but saying everyone should learn to code is like saying everyone should learn to drive manual transmission and change their own oil: cars are everywhere! Cars are the future! If you don’t drive, you will not be in control of where you are driven! This kind of alarmist propaganda is nonsensical and should be laughed out of the room. The whole point of software engineers is so other people don’t have to code!

This phenomenon coincides with a related one that also annoys me: the insinuation that being an engineer automatically demonstrates your superior intellect. The recent shortage of engineering talent in the US exacerbates this feeling, because it’s easy to conclude that the problem is because people aren’t smart enough to become software engineers. Actually, it’s mostly[1] because 1) most people think programming is about as sexy as mopping floors, and 2) for the past decade, smart people who just wanted to make money could make more for the same hours and less risk — in finance.

Software engineering is actually not that hard. There, I said it. Basic computer science type education and work is not much harder, conceptually, than intermediate calculus. The majority of the population is capable of being taught, and understanding, intermediate calculus. We know this because lots of countries teach both in middle school. QED.

This means that being a software engineer is not beyond the intellectual capacity of the average joe[2]. It also means engineers need to stop waving their diplomas around like they’re computer astronauts[3]. It makes us all look like elitist assholes, and it’s holding back our profession.


[1] Ignores our immigration problem, since it’s better if this isn’t about politics.
[2] Speaking strictly about proficiency, of course. We all know there’s a very high skill ceiling, and being a “great engineer” is a whole other ballgame. But this too has lots of external factors not related to innate skill.
[3] But don’t take this to mean we shouldn’t be proud of what we do.

Understanding Google’s Bug Bounty Program

Some people have taken Google’s idea of offering security bug bounties, and taken them to their logical conclusion: why stop at security bugs? Why not incentivize reporting of ALL software bugs with bounties? Aren’t other companies cheap for not offering bug bounties?

Questions along these lines misunderstand how software development works. Engineers don’t sit on their hands and surf Reddit after shipping a product. They’re already working on bugs. All sufficiently complex software ships with known bugs; more reporting isn’t likely to change whether they get fixed or not.

So the premise that “reporting more bugs will improve software quality” is speculative, at best. Software quality is determined by what the market will bear. The market usually rewards buggy-but-good-enough software that solves a problem now, rather than perfect solutions that are late to the party. This is partly because of the time value of software, and partly because chasing defects offers diminishing returns.

But more to the point: everyday users are not equipped to report bugs. They don’t have the training, tools, or motivation to do it properly.

At Microsoft (and other software companies), crash dumps already include as much information as can be legally collected, based on the user’s consent. So bug information for crashes and many other issues (uncaught exceptions, for example) are already being collected in an automated, accurate way. So really, any well-supported software already has built-in reporting for most high-impact bugs.

In addition, you run into other problems with bug bounties:

  • Common bugs will be over-reported, wasting everyone’s time. Customers are already motivated to report these since they want them fixed.
  • Unexpected, but by-design behavior will be incorrectly reported as bugs.
  • Problems will be exacerbated by the bounties, increasing volumes and decreasing quality. This actually creates noise around what is really important to fix (e.g., the defects users would report even if there was no bounty).
  • A bug bounty program isn’t free. Someone has to triage the input and it’s a zero sum game: either a developer does less productive work sorting through bounty submissions or headcount grows. It’s not like you can fire the testing team.

The only exception to this rule is security bugs, which operate a little bit differently than run-of-the-mill defects:

  • There is already a market for security bugs, which can be sold to hackers. The developer is simply trying to outbid them to keep the product secure.
  • This means there’s already a set of professionals who are hunting for such bugs; professionals are much more likely to find bugs on account of understanding how software is designed and implemented.
  • Users are unlikely to notice or report security bugs since they generally don’t obstruct functionality, meaning there are fewer dupes to wade through, and bug reports will be of higher quality on average.

So in my opinion, paying bounties for security bugs can be effective, but its not likely bounties for functionality bugs in the general case would be particularly productive.