Throwing an Exception in C++

Estudies4you
Throwing an Exception in C++
Q13. Explain how to throw an exception in detail. 
Answer:
An exception detected in, try block is thrown using "throw" keyword. An exception can be thrown using in following number of ways. 

throw(exception), 

throw exception; 

throw; 

Where, exception is an object of any type including a constant. The third form of Throw statement is used in rethrowing of an exception. The objects that are intended for error handling can also be thrown. 

The point at which an exception is thrown is called a throw point. When exception is thrown the control leaves the try block and it reaches to the catch block associated with the try block where the exception is handled. 
The throw point can he in a nested function call or in a nested scope within a try block. In any one of these cases the control is transferred to the catch statement

Program 

#include<iostream>

using namespace

int main()

{

int p,q;

cout<<"\nEnter the values of p and q:\n";

cin>>p>>q;

int j;

j=p>q?0:1; //condition operator that determines whether p>q, if yes assign j=0 else j=1

try

{

if(j==0) //condition that verifies whether j-0 or not

{

cout<<"substration of (p-q)<<"\n"; //perform sbustration j=0

}

else

{

throw(j); //throw exception if j?0

}

}

catch(int i)

{

cout<<"the exception is caught: j="<<j<<"\n"; //display the detected exception on screen

}

return 0;

}


Output
difference between try and throw in c++,use of try in c++,use of throw in c++,examples of throwing an exception in c++,how to throw an exception in c+


To Top