Now let's discuss exception handling ↓
throw n;
throw (n);
int main()
{
try{
...
}
catch(Exception1 obj)
{
...
}
catch(Exception2 obj)
{
...
}
return 0;
}
Let's understand with program
#include <iostream>
using namespace std;
int main()
{
int a, b, r;
cout << "Enter the value of a : ";
cin >> a;
cout << "Enter the value of b : ";
cin >> b;
if (b != 0)
r = a / b;
else
{
cout << "Cannot divide by zero";
}
return 0;
}
Output ↓
Enter the value of a : 12
Enter the value of b : 0
Cannot divide by zero
Now we will implement it using try and catch block
#include <iostream>
using namespace std;
int main()
{
int a, b;
float r;
cout << "Enter the value of a : ";
cin >> a;
try
{
cout << "Enter the value of b : ";
cin >> b;
if (b == 0)
throw 0;
r = a / b;
cout << "The result if : " << r << endl;
}
catch (int)
{
cout << "cannot divide by zero" << endl;
}
return 0;
}
Output ↓
Enter the value of a : 14
Enter the value of b : 0
cannot divide by zero
Enter the value of a : 15
Enter the value of b : 3
The result is : 5
Reference ↓