C++ uses three new keywords namely, throw, try, and catch to handle exceptions. When a function returns using the exception handling mechanism, it is referred to as throwing an exception.
The Keyword throw implements this “return” activity. The keyword try prefaces a block of statements which may generate exceptions. A catch block defined by the keyword catch ‘catches’ the exceptions ‘thrown’ by throw and handles them appropriately.
The “try” block code normally invokes a function that detects an exception. The function which is in the “throw” block returns (“throw”) the control to the “catch” block. The catch block may have more than one catch statements, each corresponding to a particular type of exception. For example, if the throw blocks is likely to throw two exceptions, the catch block will have two catch statements, one for each type of exception. Each catch statements is called an exception handler.
The function that throws the exceptions indicates the specific type of exception which in turn decides the catch statement to be executed. It is somewhat similar to a switch statement.
The Keyword throw implements this “return” activity. The keyword try prefaces a block of statements which may generate exceptions. A catch block defined by the keyword catch ‘catches’ the exceptions ‘thrown’ by throw and handles them appropriately.
The “try” block code normally invokes a function that detects an exception. The function which is in the “throw” block returns (“throw”) the control to the “catch” block. The catch block may have more than one catch statements, each corresponding to a particular type of exception. For example, if the throw blocks is likely to throw two exceptions, the catch block will have two catch statements, one for each type of exception. Each catch statements is called an exception handler.
The function that throws the exceptions indicates the specific type of exception which in turn decides the catch statement to be executed. It is somewhat similar to a switch statement.
Example for Exception Handling
#include <>
#include <>
void xcep(int n)
{
try
{
if(n!=0) throw n;
else throw “Zero”;
}
catch (int I)
{
cout<<”caught an int” <<>
#include <>
#include <>
void xcep(int n)
{
try
{
if(n!=0) throw n;
else throw “Zero”;
}
catch (int I)
{
cout<<”caught an int” <<>
}
catch(char *st)
{ cout<<”caught a string” <<>
}
}
main() { xcep(1);
xcep(2);
xcep(0);
//return 0;
}
No comments:
Post a Comment