The C++ exception system is similar to Java's,
especially in syntax. Exceptions in
a
try block are caught by the associated
catch blocks.
Some differences from Java:
- C++ uses exceptions much more sparingly than Java. The standard
libraries are in rather less of a hurry to throw them.
- The C++ standard libraries throw types
derived
from std::exception.
- Most standard exceptions you will actually encounter are derived from
std::logic_error or
std::runtime_error.
- Throwing a new object Java-style pretty much never makes sense.
In C++,
throw runtime_error("Something Went Wrong");
not the Java-style
throw new RuntimeException("This Was Not Supposed To Happen");
- Catching is usually by reference.
catch(exception &e);
- Exceptions do not convert to string, but the standard ones have a
what() method instead.
While the standard libraries throw only classes
derived
from std::exception, the language allows the throwing of
any type at all. This is not a very useful feature, and we will not
explore it.
Plain C does not support exceptions.
Textbook: Chapter 13. The program on p. 495 said to “prevent” the
throwing of exceptions simply uses some code introduced previously which
checks the input values so that the exception is not raised.
The text does discuss throwing of non-exception types if you are interested.
[more info]