Exception Handling
Exception Handling
Exception Handling
try: Represents a block of code that can throw an exception. We can define a block
of code to be tested for errors while it is being executed.
throw: Used to throw an exception. Also used to list the exceptions that a function
throws but doesn’t handle itself.
Example1
#include <iostream>
using namespace std;
int main()
{
int x = -1;
Output:
Before try
Inside try
Exception Caught
After catch (Will be executed)
Example2
include <iostream>
using namespace std;
int main()
{
try {
throw 10;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
Output:
Default Exception
Example3
If an exception is thrown and not caught anywhere, the program terminates abnormally. For
example, in the following program, a char is thrown, but there is no catch block to catch the
char.
#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught ";
}
return 0;
}
Output:
terminate called after throwing an instance of 'char'
Example 4
In C++, try/catch blocks can be nested. Also, an exception can be re-thrown using throw; .
#include <iostream>
using namespace std;
int main()
{
try {
try {
throw 20;
}
catch (int n) {
cout << "Handle Partially ";
throw; // Re-throwing an exception
}
}
catch (int n) {
cout << "Handle remaining ";
}
return 0;
}
Output:
Handle Partially Handle remaining
Example 5
When an exception is thrown, all objects created inside the enclosing try block are
destroyed before the control is transferred to the catch block .
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "Constructor of Test " << endl; }
~Test() { cout << "Destructor of Test " << endl; }
};
int main()
{
try {
Test t1;
throw 10;
}
catch (int i) {
cout << "Caught " << i << endl;
}
Output:
Constructor of Test
Destructor of Test
Caught 10