What are the basics of throwing and catching exceptions in C++?

 
 

Exceptions are for handling errors. If a function cannot fulfill its promises for some reason, it should throw an exception. This style of reporting errors is different from the way many other programming languages report errors—many languages use a return code or error code that the caller is supposed to explicitly test. However C++ uses three defined keyword try, catch and throw in order to throw and catch exceptions.
try and catch are keywords. The code within the block after the try keyword is executed first. If there are no problems executing the try block then the runtime system proceeds executing the try block and skips the catch blocks and proceeds normally. In the case when an exception is thrown, control immediately jumps to the matching catch block. If there is no matching catch block in the caller, control immediately jumps back to the matching catch block in the caller's caller, caller's caller's caller, and so on, until it reaches the catch(...) block in main () .
The throw keyword is used to throw an exception whenever the code needs to. The throw () declarations after the signature of the various functions are the function's way of telling callers what it might throw.