NOTE -- This program is in the file exceptn.cpp.
This following example program demonstrates the use of exceptions:
#include <stdexcept> #include <string> static void f() { throw std::runtime_error("a runtime error"); } int main () { std::string s; // First we'll try to incite then catch an exception // from the Standard C++ Library string class. // We'll try to replace at a position that is non-existent. // // By wrapping the body of main in a try-catch block we can be // assured that we'll catch all exceptions in the exception // hierarchy. You can simply catch an exception as is done // below, or you can catch each of the exceptions in which // you have an interest. try { s.replace(100,1,1,'c'); } catch (const std::exception& e) { std::cout << "Got an exception: " << e.what() << std::endl; } // Now we'll throw our own exception using the function // defined above. try { f(); } catch (const std::exception& e) { std::cout << "Got an exception: " << e.what() << std::endl; } return 0; }