CPP Unit-V
CPP Unit-V
In C++, exception is an event or object which is thrown at runtime. All exceptions are derived from
std::exception class. It is a runtime error which can be handled. If we don't handle the exception, it prints
exception message and terminates the program.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed even after
exception.
Exception Description
o try
o catch, and
o throw
The try statement allows you to define a block of code to be tested for errors while it is
being executed.
The throw keyword throws an exception when a problem is detected, which lets us create a
custom error.
The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.
#include <iostream>
using namespace std;
int main() {
try {
int age = 20;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}
Example explained
We use the try block to test some code: If the age variable is less than 18, we will throw an
exception, and handle it in our catch block.
In the catch block, we catch the error and do something about it. The catch statement
takes a parameter: in our example we use an int variable (myNum) (because we are
throwing an exception of int type in the try block (age)), to output the value of age.
If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater than 18),
the catch block is skipped:
#include <iostream>
int main() {
try {
} else {
throw 505;
return 0;
OUTPUT:
When an exception is thrown, it is caught by its corresponding catch statement, which processes
the exception. There can be more than one catch statement associated with a try. Which catch
statement is used is determined by the type of the exception. That is, if the data type specified
by a catch matches that of the exception, then that catch statement is executed (and all others
are bypassed). When an exception is caught, arg will receive its value. Any type of data may be
caught, including classes that you create. If no exception is thrown (that is, no error occurs
within the try block), then no catch statement is executed.
throw exception;
throw generates the exception specified by exception. If this exception is to be caught, then
throw must be executed either from within a try block itself, or from any function called from
within the try block (directly or indirectly).
#include <iostream>
int main()
try
catch (int i)
{ // catch an error
return 0;
}
Start
End
#include <iostream>
int main()
return 0;
This program produces the following output because the integer exception will not be
caught by the catch(double i) statement. (Of course, the precise message describing
Start
An exception can be thrown from outside the try block as long as it is thrown by
a function that is called from within try block. For example, this is a valid program.
try block.
*/
#include <iostream>
cout << "Inside Xtest, test is: " << test << "\n";
int main()
Xtest(0);
Xtest(1);
Xtest(2);
}
return 0;
Start
End
A try block can be localized to a function. When this is the case, each time the
function is entered, the exception handling relative to that function is reset. For
#include <iostream>
try{
catch(int i) {
int main()
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
return 0;
Start
Caught Exception #: 1
Caught Exception #: 2
Caught Exception #: 3
End
An exception can be of any type, including class types that you create. Actually, in
real-world programs, most exceptions will be class types rather than built-in types.
Perhaps the most common reason that you will want to define a class type for an
exception is to create an object that describes the error that occurred. This information
can be used by the exception handler to help it process the error. The following
#include <iostream>
#include <cstring>
class MyException {
public:
char str_what[80];
int what;
strcpy(str_what, s);
what = e;
};
int main()
int i;
try {
cin >> i;
if(i<0)
return 0;
Not Positive: -4
The program prompts the user for a positive number. If a negative number is entered,
an object of the class MyException is created that describes the error. Thus,
MyException encapsulates information about the error. This information is then used by
the exception handler. In general, you will want to create exception classes that will
encapsulate information about an error to enable the exception handler to respond
effectively
As stated, you can have more than one catch associated with a try. In fact, it is common
to do so. However, each catch must catch a different type of exception. For example,
#include <iostream>
try{
catch(int i) {
int main()
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
return 0;
Start
Caught Exception #: 1
Caught Exception #: 2
Caught a string: Value is zero
Caught Exception #: 3
End
As you can see, each catch statement responds only to its own type.
In general, catch expressions are checked in the order in which they occur in a
program. Only a matching statement is executed. All other catch blocks are ignored.
In some circumstances you will want an exception handler to catch all exceptions
instead of just a certain type. This is easy to accomplish. Simply use this form of catch.
catch(...) {
Here, the ellipsis matches any type of data. The following program illustrates catch(...).
#include <iostream>
try{
int main()
Xhandler(0);
Xhandler(1);
Xhandler(2);
return 0;
Start
Caught One!
Caught One!
Caught One!
End
As you can see, all three throws were caught using the one catch statement.
One very good use for catch(...) is as the last catch of a cluster of catches. In this
capacity it provides a useful default or "catch all" statement. For example, this slightly
different version of the preceding program explicity catches integer exceptions but
You need to be careful how you order your catch statements when trying to catch exception types
that involve base and derived classes because a catch clause for a base class will also match any
class derived from that base. Thus, if you want to catch exceptions of both a base class type and a
derived class type, put the derived class first in the catch sequence. If you don't do this, the base
class catch will also catch all derived classes. For example, consider the following program.
#include <iostream>
class B {
};
class D: public B {
};
int main()
D derived;
try {
throw derived;
catch(B b) {
catch(D d) {
return 0;
}
Here, because derived is an object that has B as a base class, it will be caught by the first catch
clause and the second clause will never execute. Some compilers will flag this condition with a
warning message. Others may issue an error. Either way, to fix this condition, reverse the order of the
catch clauses.
Rethrowing an Exception
#include <iostream>
void Xhandler()
try {
int main()
Xhandler();
catch(const char *) {
return 0;
Start
End
OTHER EXAMPLES:
#include<iostream>
#include<conio.h>
int main()
int a,b;
try
cout<<"enter tw numbers";
cin>>a>>b;
if(b==0) throw 0;
cout<<"division="<<a/b;
catch(int x)
} //main close
~test()
{
cout<<"i am the destructor\n";
}
};
int main()
{
try
{
cout<<"welcome to exception handling\n";
test t;
throw 10;
cout<<"testing destructor\n";
}
catch(...)
{
cout<<"thank you";
}
}
C++ try/catch
In C++ programming, exception handling is performed using try/catch statement. The C++ try block is
used to place the code that may occur exception. The catch block is used to handle the exception.
Output:
Output:
#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception{
public:
const char * what() const throw()
{
return "Attempted to divide by zero!\n";
}
};
int main()
{
try
{
int x, y;
cout << "Enter the two numbers : \n";
cin >> x >> y;
if (y == 0)
{
MyException z;
throw z;
}
else
{
cout << "x / y = " << x/y << endl;
}
}
catch(exception& e)
{
cout << e.what();
}
}
Output:
Output:
Note: In above example what() is a public method provided by the exception class. It is used to return
the cause of an exception.
Example Code
#include <iostream>
throw 100;
function1();
catch(int i) {
int main() {
function3();
return 0;
Output
Entering function 3
Entering into function 2
Entering into function 1
Caught Exception: 100
Exiting function 3
Here we can see that the control stores info of function3, then enters into function2, and then into
function1. After that one exception occurs, so it removes all of the information from stack, and returns
back to function3 again.