Problem:
Write a program containing a possible exception.Use a try block to throw it and a catch block to handle it properly.
Solution:
#include<iostream>
using namespace std;
main()
{
int i,fact=1;
cout<<"Enter A Positive No To Calculate Factorial\n";
cin>>i;
try
{
if(i<0)
{
throw i;
}
else
{
for(int j=1;j<=i;j++)
fact=fact*j;
cout<<"\nFactorial="<<fact;
}
}
catch(int)
{
cout<<"Number Not Valid";
}
cout<<"\nEnd";
}
Output:
Write a program containing a possible exception.Use a try block to throw it and a catch block to handle it properly.
Solution:
#include<iostream>
using namespace std;
main()
{
int i,fact=1;
cout<<"Enter A Positive No To Calculate Factorial\n";
cin>>i;
try
{
if(i<0)
{
throw i;
}
else
{
for(int j=1;j<=i;j++)
fact=fact*j;
cout<<"\nFactorial="<<fact;
}
}
catch(int)
{
cout<<"Number Not Valid";
}
cout<<"\nEnd";
}
Output: