Chapter 22. Exceptions
How glorious it isâand also how painfulâto be an exception.
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 ...
Get Practical C++ Programming, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.