TRY BLOCK in C++
Q14. Discuss in brief about the try block.
Answer:
Try Block
Try is a keyword that is used to detect the exceptions i.e.., run time errors. The statements that generates exceptions are kept inside the try block. The runtime errors can be handled and prevented using try block. The general syntax of try block is as follows,
try
{
//code
throw exception
}
A try block can throw more than one exception. There should he a catch block to handle the exceptions thrown by try block.
Example
#include<iostream>
using namespace std;
void square( ) //A function called square is defined
{
int num;
cout<<"Enter a number:";
cin>>num;
if(num>0) //This condition checks whether number is
greater than zero or not
{
cout<<"Square of the number is:"
<<num*num<endl; //Compute the square of number and display the result
on screen
else
throw(num); //if number<0 throw an exception.
int main()
{
try
{
square();
square();
}
catch(int i) //This statement catches an exception
{
cout<<"Exception caught\n":
}
return 0:
}
Output