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. (Like the concept of β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:
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.
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.
You can think of exceptions as a separate communication path a function can use: a function can either return a normal value, or it can choose to throw an exception. It will never do both.
You have attempted of activities on this page.
