Example & Tutorial understanding programming in easy ways.

What is try in C++ ?

Try and catch are the keyword in C++ which are used to handle the exception in the program.

Try:
We put that part of program inside the try block in which there is a chance of exception or error.

Catch:
If there is an exception in try block then control goes on Catch block.

Without exception handling:

program:

#include< iostream>
int main()
{
int n=10,num;
cout<<"Enter number to divide 10"<< endl;
cin>>num;
n=n/num;
cout<< n;
}


output-

Enter number to divide 10
0
error

-In this program, when control gies on 'n=n/0', then program terminated or give run time error which is problem.

Solve this problem:

program:

#include< iostream>
int main()
{
int n=10,num;
cout<<"Enter number to divide 10"<< endl;
cin>>num;
try:
n=n/num;
cout<< n;
catch:
cout<<"Wrong operation!,It is divisible by zero";
}


output-

Enter number to divide 10
0
Wrong operation!,It is divisible by zero

-In this program, when error arives then program not close ,the control goes on catch block then it execute correctly.




Read More →