Section 1 - Guarded Code

5B.1.1 Exceptions Thrown By C++

What happens if we run this program?

#include <iostream>
using namespace std;

// main method ---------------------------------------
int main()
{
  int a = 0, b = 0, result;

  a = 10;
  result = a / b;
  cout << result << endl;

  b = -5;
  result = a / b;
  cout << result << endl;

  return 0;
}

Don't be afraid.  Paste it into your project and try it out.  You can try the usual start without debugging, or even try start with debugging.  The latter will give you a hint about what went wrong.  (When you start a program with debugging, you have to sometimes select Debug -> Stop Debugging to get back to your IDE).

The problem, of course, is that we cannot divide by 0.  There is no answer.  Furthermore, once the first div. by 0 error occurs, the program doesn't know what to do next, and must abort.

C++ is throwing an exception and we are not catching it.  That means, inside the / operator implementation, C++ decided that we asked it to do something that it cannot possibly do, and there is no way for it to signify that with:

So it throws an exception and returns.  If our client does not catch the exception, the program terminates.  So how do we catch it?  With a try/catch block.

cop car

5B.1.2 Try/Catch Blocks

The beauty of exceptions is that you don't have to test the result of a dangerous method call at the instant you call it.  Let's say functions, skyDive(), rideMotorcycles() and smoke10PacksADay() are all functions that could generate errors, and each has a bool return type to report back the status of the call.    The ugly code to call these methods from the client would look a little like this:

if (!skyDive())
{
  // handle errors
}
else
{
  // do normal stuff
}
if (!rideMotorcycles())
{
  // handle errors
}
else
{
  // do normal stuff
}
if (!smoke10PacksADay())
{
  // handle errors
}
else
{
  // do normal stuff
}

With a try/catch block we write the code, instead like this:

try
{
  skyDive();
  // do normal stuff
  rideMotorcycles();
  // do normal stuff
  smoke10PacksADay();
  // do normal stuff
}
catch(...)
{
  // handle errors
}

The section inside the try block is called the try clause or a guarded section of code.   If an exception is thrown from inside any one of these methods, normal program flow stops and control passes to the start of the catch block, or the exception handler.  If no exceptions are thrown anywhere inside the try clause, the catch clause is skipped and control continues after it.