Skip to Main Content
Practical C++ Programming, 2nd Edition
book

Practical C++ Programming, 2nd Edition

by Steve Oualline
December 2002
Beginner to intermediate content levelBeginner to intermediate
576 pages
14h 6m
English
O'Reilly Media, Inc.
Content preview from Practical C++ Programming, 2nd Edition

Chapter 22. Exceptions

How glorious it is—and also how painful—to be an exception.

Alfred de Musset

Airplanes fly from one place to another and 99.9% of the time there’s no trouble. But when there is trouble, such as a stuck wheel or an engine fire, pilots are trained to handle the emergency.

Let’s examine in detail what happens during an airborne emergency such as an engine catching fire. This is an exception to normal flight. First, a fire alarm goes off in the cockpit. The alarm catches the pilots’ attention, and they start going through the fire-emergency procedure. This is an extensive list of things to do in case of fire. The airline prepared this list ahead of time, and the pilots have the list memorized. The pilots do what’s necessary to handle the exception: activate the fire extinguisher, shut down the engine, land very quickly, etc.

Let’s translate this procedure into C++ pseudocode. When the pilots take off they are going to try to fly the plane from one point to another without problems. The C++ “code” for this is:

try {
     fly_from_point_a_to_point_b(  );
}

The try keyword indicates that we are going to attempt an operation that may cause an exception.

But what happens when we get an exception? We need to handle it. The C++ code for this is:

catch (fire_emergency& fire_info) {
    active_extinguisher(fire_info.engine);
    turn_off(fire_info.engine);
    land_at_next_airport(  );
}

The keyword catch indicates that this section of code handles an exception. In this case the exception handled ...

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.
Start your free trial

You might also like

Discovering Modern C++, 2nd Edition

Discovering Modern C++, 2nd Edition

Peter Gottschling

Publisher Resources

ISBN: 0596004192Supplemental ContentErrata Page