Skip to main content

Section 10.10 Exception Throwing

When using exceptions, code that detects a problem which it cannot handle should throw an exception. You can do so by using the throw keyword followed by what you want to throw. Although you can thrown anything (an int, string, etc...). It is generally best to throw some type of exception.
exception itself is what is known as an abstract data type. It is a type that describes many more specific types, but nothing is just an exception. (Similar to β€œanimal”. β€œanimal” describes many different types of creature, but nothing is just an β€œanimal”. Each particular animal is a dog, or a cat, or a horse.)
Thus we need to throw something more specific like a logic_error. To do that, we say throw logic_error(STRING);. The STRING should be a string that describes what went wrong. This sample shows mediumJob throwing a logic_error:
Listing 10.10.1.
In this version of the program, the author of mediumJob wrote logic to check for the conditions that would lead to an error. If things do not look good, the function throws the exception (line 10). This ends execution of mediumJob and immediately jumps back to bigJob to see if the exception is caught there.

Note 10.10.1.

One a function throws an exception, no more code will run and no value will be returned via any return statements. A throw represents a function completely giving up on its job.

Insight 10.10.2.

logic_error is a good catchall for β€œsomething does not make sense here”. There may be times when some other type of exception makes more sense, but we will generally just throw a logic_error when throwing exceptions in this book.

Checkpoint 10.10.1.

You have attempted of activities on this page.