Exceptions

In C++, an exception is the computer’s response to a problem that occurs while executing a program’s code. The computer will create an exception, and if the code does not have a way to handle it, then the program will stop executing due to the error.

Catching an Exception

The function getString() as defined below will throw an exception if you try to access an index outside the allowable bounds.

Code
Output
Loading...

Errors, when uncaught, will cause your program to immediately stop. This behavior can be prevented by wrapping the code which might emit an error in a try block, and providing at least one catch block to execute if the code throws the error. Look at the improvement below:

Code
Output
Loading...

The parenthesized ellipsis above indicate that the catch should try to catch any and all errors. It is possible be more specific by replacing the ellipsis with the error type that would be thrown for common inputs:

  • catch (std::length_error) would catch the specific error that will be thrown
  • catch (std::length_error errorName) would not only catch the same error, but give us access to the error object inside the catch block with the variable errorName

It is possible to catch multiple types of exception by specifying multiple catch blocks:

int main() {
try {
// Code goes here
}
catch (int intErrorVariable) {
// The thrown error was of type int
}
catch (std::exception exceptionVariable) {
// The thrown error was of type exception
std::cout << exceptionVariable.what();
}
catch (...) {
// The ellipsis
}
}

This example also names the exceptions so that you might access the exception during the catch block. If the exception is of type std::exception (or one of the classes which inherit from it), you can call .what() on the caught exception to read the error message.

Throwing an Exception

While one side of the exceptional coin is catching exceptions, the other side is throwing them. Since user input is often unpredictable, it is important to handle bad data with grace.

The sqrt() funciton provided by the math.h library calculates square roots, however it will return nan for the square root of negative numbers. The example below creates a custom mySqrt() function so that an execption is thrown when a negative number is passed in as a parameter. This allows us to catch it in our main block rather than testing if the returned valued is equal to nan.

While it is possible to use throw with many data types, it is common to throw a runtime error. The syntax can be seen in the example below:

Code
Output
Loading...

This program will run, and output the following:

Square root of 4.41 is 2.1
ERROR: Negative numbers not allowed

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn C++ on Codecademy

Contributors