Advertisement
#include<iostream>
using namespace std;
int main()
{
int a=10, b=0, c;
try
{
//if a is divided by b(which has a value 0);
if(b==0)
throw(c);
else
c=a/b;
}
catch(int a) //matching int type of exception is declared in "catch block"
{
cout<<"An exception caught : division by zero \n"; //message related to caught exception is printed
}
cout<<"Outside try-catch block";
return 0;
}
An exception caught : division by zero
Outside try-catch block
Advertisement
#include<iostream>
#include<string>
using namespace std;
int main()
{
char arr[5];
try
{
for (int n=0; n<=6; n++)
{
if (n>4)
throw std::string("out-of-range");
else
arr[n]='a';
}
}
catch (std::string st)
{
std::cout << "Exception caught : " << st;
}
return 0;
}
Exception caught : out-of-range
#include<iostream>
using namespace std;
class TryCatch2
{
public:
void meth();
};
void TryCatch2 :: meth()
{
try
{
int a = 10;
int b = 10;
int result = a-b;
if(result==0)
throw(b);
else
cout<<(100/result);
}
catch(double c) //Non-matching exception-type is declared in this catch block
{
cout<<"Caught exception type : double type \n";
}
cout<<"Outside try-catch block";
} //meth1() function ends
int main()
{
TryCatch2 ob;
try
{
ob.meth(); //enclosing the call to meth1() function in try block
}
catch(int c)
{
cout<<"Caught exception : int type \n" ;
}
} //main function ends
Caught exception : int type
#include<iostream>
using namespace std;
int main()
{
try
{
int a = 10;
int b = 10;
int result = a-b;
if(result==0)
throw(b);
else
cout<<(100/result);
}
//cout<<"Statement between try-catch"; //Statement between try-catch block leads to compile error
catch(int e)
{
cout<<"Caught exception : int type \n" ;
}
}
c142.cpp: In function 'int main()':
A.cpp:18:1: error: expected 'catch' before 'cout'
cout<<"Statement between try-catch"; //Statement between try-catch block leads
to compile error
^~~~
A.cpp:18:1: error: expected '(' before 'cout'
A.cpp:18:1: error: 'cout' does not name a type
A.cpp:18:5: error: expected ')' before '<<' token
cout<<"Statement between try-catch"; //Statement between try-catch block leads
to compile error
^~
A.cpp:18:5: error: expected '{' before '<<' token
A.cpp:18:5: error: expected primary-expression before '<<' token
A.cpp:19:1: error: expected primary-expression before 'catch'
catch(int e)
^~~~~
#include<iostream>
using namespace std;
int main()
{
try
{
int a = 10;
int b = 10;
int result = a-b;
if(result==0)
throw(b);
else
cout<<(100/a-b);
}
}
c143.cpp: In function 'int main()':
c143.cpp:19:1: error: expected 'catch' before '}' token
}
^
c143.cpp:19:1: error: expected '(' before '}' token
c143.cpp:19:1: error: expected type-specifier before '}' token
c143.cpp:19:1: error: expected ')' before '}' token
c143.cpp:19:1: error: expected '{' before '}' token
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement