C++ Program on Exception Handling
Master C++ with Real-time Projects and Kickstart Your Career Start Now!!
Program 1
#include<iostream>
#include<stdexcept>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter two number";
cin>>a>>b;
try
{
if(b==0)
throw(runtime_error("Can not devide by Zero"));
c=a/b;
cout<<c;
}
catch(const std::exception &e)
{
std::cerr << e.what() << '\n';
}
c=a-b;
cout<<"\n"<<c ;
c=a+b;
cout<<"\n"<<c ;
c=a*b;
cout<<"\n"<<c ;
}Program 2
#include<iostream>
#include<stdexcept>
using namespace std;
int main()
{
int a[5],n,i;
cout<<"Enter the limit of array";
cin>>n;
try
{
if(n>5)
throw(runtime_error("Array Index out of bound..."));
cout<<"Enter "<<n << " Elements in array";
for(i=0;i<n;i++)
cin>>a[i];
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
}Program 3
#include<iostream>
#include<stdexcept>
using namespace std;
class ATM
{
private:
int amount;
public:
ATM()
{
amount=0;
}
void deposit(int amt)
{
try
{
if(amt<=0)
throw(invalid_argument("\nInvalid amount for deposit...."));
amount=amount+amt;
cout<<"\nAccount Balance: "<<amount;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
}
void withd(int amt)
{
try
{
if(amt>amount)
throw(runtime_error("\nInsufficient balance "));
if(amt<=0)
throw(invalid_argument("\nInvalid amount..."));
amount=amount-amt;
cout<<"\nAccount Balance: "<<amount;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
}
};
int main()
{
int choice,a;
ATM A;
do
{
cout<<"\n----------ATM MENU--------------";
cout<<"\n 1. Deposit";
cout<<"\n 2. Withdrawal";
cout<<"\n 3. Exit";
cout<<"\n---------------------------------";
cout<<"\n Enter your choice";
cin>>choice;
switch(choice)
{
case 1:
{
cout<<"\n Enter an amount for deposit";
cin>>a;
A.deposit(a);break;
}
case 2:
{
cout<<"\n Enter an amount for withdrawal";
cin>>a;
A.withd(a);break;
}
case 3:break;
}
}while(choice!=3);
return 0;
}
Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

