Programming in C ++

Announcements

Articles

Programming in C ++

Programming in C ++

C++ - Exceptions

What is Exceptions?

An exception is an unusual event that happens in a program under certain circumstances, which is beyond the control of the program. Exceptions mainly occur in memory and file operations.

Exceptions handling is a C++ feature that enables a program to intercept and process exceptional conditions –errors, usually –in an orderly, organized and consistent manner. Exception handling allows one section of a program to sense and dispatch error conditions, and another section to handle them. Using C++ exception handling, the program can automatically invoke error-handling routines when an error occurs. The user can specify a list of exceptions that a function may throw as a part of function declaration.

Exceptions handling fundamentals:

 A C++ exception is built upon three keywords try, catch and throws. In the most general terms, that to be monitored for exceptions is contained in a try block. If an exception occurs within the try block, it is thrown (using throw statement). The exception is caught, using catch, and processed.

The general forms of try and catch are shown here

try

{

//try block

}

catch (data_type arg)

{

//catch block

}

catch (data_type2 arg)

{

//catch block

} catch(data_typeN arg)

{

//catch block

}

Using multiple catch statements:

You can have more than one-catch statements, but each catch statement must catch a different data type. The number of catch statements cannot be exceed the number of data types supported by the language.

Example:

#include<iostream.h>

void xcep(int n)

{

try{

if(n!=0) throw n;

else throw “zero”;

}

catch(int i)

{

cout<<”Caught an int”<< i<< endl;

}

catch(char *st)

{

cout <<”caught a string “<<st<<endl;

}

}

main()

{

xcep(1);

xcep(2);

xcep(0);

return 0;

}