Exceptions & Error Handling

Error Handling

This section also applies to C programs. [Not all covered in Fall 2025.]

exit(int)

abort()

assert(condition)

Example:

    Point *parray;
    parray = new Point[6];
    if (parray == 0) { 
        cerr << "not enough memory for point array";
        exit(EXIT_FAILURE);
    }
    assert(parray != 0);

Exceptions

What are exceptions?

How exceptions are processed at run-time

Simple example:

#include <iostream>

int bust(int n) throw (std::overflow_error) // declare exception raised in bust
{
    std::cout << "calling function bust(" << n << ")" << std::endl;
    if (n >100000) throw std::overflow_error("buuusted!");
    std::cout << "finishing function bust" << std::endl;
    return 0;
};
    
void must(int n) throw (std::overflow_error) // since must does not catch, bust exception also declared here
{
    bust(n);
    std::cout << "finishing running must, bust did not throw exception" << std::endl;
};

int main ()
{
    try
    {  must(33);  }
    catch (std::exception & e)
    { std::cout << "caught exception HERE!" << std::endl; } // doesn't run

    try
    {  must(8723643);  }
    catch (std::exception & e)
    {    std::cout << "caught exception THERE!" << std::endl; }

    std::cout << "program still keeps running since exception caught" << std::endl;
}

Options for declaring in the header which exceptions a function can throw

What C++ does with these declarations

Making your own exception objects

An example of a user-declared exception type:

#include <iostream>
#include <exception>

class boom: public std::exception {
   virtual const char* what() const throw() // override what() to customize error string
      {  return "BOOM!";  }
};

int main ()
{
    boom myex;
    try
    {  throw myex;  }
    catch (std::exception & e)
    {
        std::cout << "Exception what code is: " << e.what() << std::endl;
    }
}

Observe about the above: