Throwing mechanism in Exception Handling:
When an exception that is desired to be handled to be detected. It is throw using the throw statement in one of the following forms.
1. throw (exception);
2. throw ; //used for re-throwing an exception.
The operand object exception may be of any type, including constants. It is also possible to throw objects not intended for error handling. When an exception is throw, It will be caught by the catch statement associated with the try block. That is the control exits the current try block, and is transferred to the catch block after that try block. Throw point can be in deeply nested scope with a try block or in a deeply nested function call. In any case, control is transferred to the catch statement.
Program for throw exception in a program code:
#include<iostream>
using namespace std;
void divide()
{
int a, b, x;
cout<<"Enter two numbers\n";
cin>>a>>b;
if(b==0)
{
throw(a);
}
else
{
ex = a/b;
cout<<a<<"/"<<b<<" ="<<x;
}
}
void main()
{
try
{
divide()
}
catch(int i)
{
cout<<"Divide by zero";
}
}
Output 1
Enter two numbers
10
5
10/5 = 2
Output 2
Enter two numbers
10
0
Divide by zero error.
Post A Comment:
0 comments: