O'Reilly logo

Practical C++ Programming, 2nd Edition by Steve Oualline

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required