xxxxxxxxxx
// C++ program to demonstate the use of try,catch and throw
// in exception handling.
#include <iostream>
using namespace std;
int main()
{
int x = 1;
// Some code
cout << "Before try \n";
// try block
try {
cout << "Inside try \n";
if (x < 0) {
// throwing an exception
throw x;
cout << "After throw (Never executed) \n";
}
}
// catch block
catch (int x) {
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
return 0;
}
xxxxxxxxxx
try {
throw 10; //Error Detected and "Thrown" to catch block
}
catch (char *excp) { //if error is thrown matches this block, exec
cout << "Caught " << excp;
}
catch ( ) { //default case
cout << "Default Exception\n";
}
xxxxxxxxxx
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x=-1,y=1;
try
{
if(x<0)
{
throw("xisnegative");
}
}
catch(const char *exp)
{
cout<<exp<<endl;
}
try
{
if(y>0)
{
throw("yispositive");
}
}
catch(const char *exp)
{
cout<<exp<<endl;;
}
return 0;
}