exception handling in c++

Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.
To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.
An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block:


// A simple exception handling example.
#include <iostream>
using namespace std;

int main()
	cout << "Start\n";

	{ // start a try block
		cout << "Inside try block\n";
		throw 100; // throw an error
		cout << "This will not execute";
	} catch (int i)
	{ // catch an error
		cout << "Caught an exception -- value is: ";
		cout << i << "\n";

	cout << "End";

	return 0;

You may also like...