You are on page 1of 14

An exception is a problem that arises during the execution of a program.

A C++ exception is a response to an exceptional circumstance that arises


while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program


to another. C++ exception handling is built upon three keywords: try,
catch,and throw.

throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

catch: A program catches an exception with an exception handler at the place in a program where you want to
handle the problem. Thecatch keyword indicates the catching of an exception.

try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or
more catch blocks.

Assuming a block will raise an exception, a method catches an exception


using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following:

try

// protected code

}catch( ExceptionName e1 )

// catch block

}catch( ExceptionName e2 )

// catch block

}catch( ExceptionName eN )

// catch block

You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
different situations.

Throwing Exceptions:
Exceptions can be thrown anywhere within a code block
using throwstatements. The operand of the throw statements
determines a type for the exception and can be any expression and the
type of the result of the expression determines the type of exception
thrown.

Following is an example of throwing an exception when dividing by zero


condition occurs:

double division(int a, int b)


{

if( b == 0 )

throw "Division by zero condition!";

return (a/b);

Catching Exceptions:
The catch block following the try block catches any exception. You can
specify what type of exception you want to catch and this is determined
by the exception declaration that appears in parentheses following the
keyword catch.

try

// protected code

}catch( ExceptionName e )

{
// code to handle ExceptionName exception

Above code will catch an exception of ExceptionName type. If you want


to specify that a catch block should handle any type of exception that is
thrown in a try block, you must put an ellipsis, ..., between the
parentheses enclosing the exception declaration as follows:

try

// protected code

}catch(...)

// code to handle any exception

The following is an example, which throws a division by zero exception


and we catch it in catch block.

#include <iostream>

using namespace std;

double division(int a, int b)

if( b == 0 )

throw "Division by zero condition!";

return (a/b);

int main ()

{
int x = 50;

int y = 0;

double z = 0;

try {

z = division(x, y);

cout << z << endl;

}catch (const char* msg) {

cerr << msg << endl;

return 0;

Because we are raising an exception of type const char*, so while


catching this exception, we have to use const char* in catch block. If we
compile and run above code, this would produce the following result:

Division by zero condition!

C++ Standard Exceptions:


C++ provides a list of standard exceptions defined
in <exception> which we can use in our programs. These are arranged
in a parent-child class hierarchy shown below:
Here is the small description of each exception mentioned in the above
hierarchy:

Exception Description

std::exception An exception and parent class of all the standard C++


exceptions.

std::bad_alloc This can be thrown by new.

std::bad_cast This can be thrown by dynamic_cast.

std::bad_exception This is useful device to handle unexpected exceptions in a


C++ program

std::bad_typeid This can be thrown by typeid.

std::logic_error An exception that theoretically can be detected by reading


the code.

std::domain_error This is an exception thrown when a mathematically invalid


domain is used

std::invalid_argument This is thrown due to invalid arguments.


std::length_error This is thrown when a too big std::string is created

std::out_of_range This can be thrown by the at method from for example a


std::vector and std::bitset<>::operator[]().

std::runtime_error An exception that theoretically can not be detected by


reading the code.

std::overflow_error This is thrown if a mathematical overflow occurs.

std::range_error This is occured when you try to store a value which is out
of range.

std::underflow_error This is thrown if a mathematical underflow occurs.

Log in or Sign up

HomeArticles > Programming > C++ >

1. This site uses cookies. By continuing to use this site, you are agreeing
to our use of cookies. Learn More.
How to Write Multi Files Program in C++
Discussion in 'C++' started by usmanmalik, Jan 22, 2014.

1.

usmanmalikNew Member
JOINED:

Dec 28, 2013

MESSAGES:

19

LIKES RECEIVED:

14

TROPHY POINTS:
0

In my previous articles, I had introduces you to some of the fundamental concepts of the C+
+ language. However, you would have noticed that all the code we wrote, resided in a single
file. We developed object oriented programs where we used multiple classes, but all those
classes were in a single file. We also declared functions outside the main function but they
were also in the same file. This single file approach is good for understanding the basic
programming concepts at colleges of universities. However, industries dont work that way.
Once you enter IT industry or some software house, you will come across situations where
you will have to organize your code into more structured form which is easier to manage and
maintain. In such scenarios, code of a program is further divided into multiple files. Such
programs are called, multi-file programs.

Multi-file programs are those programs where code is distributed into multiple files
communicating with each other. This is a more practical and realistic approach towards
advanced programming where we want loosely coupled code module that can communicate
with each other. A question here arises that why should we prefer multi-file programs.
Advantages of using multiple files for a program are numerous. For instance, if you write
code for a class in a separate document, you can use that class in multiple programs. It
increases reusability of the code. Furthermore, if you want to change anything in a class, you
will only have to change it in that particularly document and the change will be automatically
reflected in all the documents referring to this document. Furthermore, it is advisable to write
large complex programs in multiple files. And last but not the least, in large organizations;
several programmers are working on a project. In such scenarios, each programmer is
responsible for designing designated modules; therefore separate documents for each
programmer, are convenient to code and then subsequently integrate.

In this article, I have explained the basics of using multiple files in a program. If you are
using an IDE such as Eclipse, Visual Studio, Net Beans etc., multi-file programming
becomes lot more easily. For the purpose of this article, we will be using Visual studio 2010.
We will demonstrate with the help of example, how can you can structure your code into
multiple files and how can you refer to the code in other documents. Fr

Before dwelling into the details of how we can actually write a code into multiple files, there
are few concepts that need to be explained. After you understand these concepts, it will be
much easier for you to understand the structure of multiple file programs and how they
actually interact.

Class Libraries

Till now, we have seen that in all of our programs, we have include some header files using
include keywords. Actually what happens at the backend is we are referring to some already
built C++ library. A C++ library is a compiled form of C++ classes. For instance when you
write #include <iostream> in your code, actually you are telling the compiler that you want to
use iostream class library functions in your code. Compiler come with some built in class
libraries which they place in a special folder called include. This include folder is located
deep down in compilers directory. In .NET platforms, class libraries come with extension .dll
which stands for dynamically linked libraries. It means that when you refer to the class
libraries, compiler doesnt link your code with the library. Actually what happens is that when
you run your program, compiler dynamically links the code from those libraries to your
programs code.

Initially, in structural or procedural programming languages, functions were written in


separate files and those functions were called in the main files using include keyword or
some other referring keyword. But, since the advent of object oriented programming,
programmers started to write classes in separate files. These compiled form of such
separate documents that we refer in our programs are called class libraries.

Class libraries have numerous advantages. They are ready made module encompassing
complex functionalities which help reduce programmers problems. Programmers only have
to combine these class libraries, add their own functionality and achieve desired
programming objectives. C++ has thousands of built in and third party class libraries and
their number are increasing exponentially. Some of these libraries come free and are open
source where as others are commercial. You can also write your own class libraries and
upload it to some source for free or for some price.

Interface

In order to interact with classes written by other programmers, a mechanism is required. In


C++, this is achieved via a file called header file having extension .h. Header file basically
contains the information about the classes or the functions that a file contains. The
information in header file has to be public due to the reason that is accessed by the
programmer who wants to incorporate class librarys code into his code. This header file is
known as interface. Suppose we name the code written by developer is called the
developers code where as those written by me or you are named as the programmers
code. We want to incorporate the developers code into ours programmers code. This
header file acts as a bridge between the two codes. Actually when we write #include
<classname.h>, we are not directly referring to the functionality of the class, actually we are
referring to the associated header file. Another reason why programmer provides public
functionalities is because they do not want other to pirate their code or modify it without the
prior permission of the actual developer.

Implementation

Implementation file is actually the file which contains the code written by the developer or as
aforementioned the developers code which we access using the header file. The
implementation is often times hidden from us so that we do not modify this piece of code.

Now, we have seen three fundamental concepts in multi-file programming in C++. We will
give you a more practical demonstration of how actually multi-file programming works. We
will explain the concept with help of following examples.

Note: We will be writing our code in Visual C++ in Visual Studio 2010.

We will create a win32 console application. If you look at the solution explorer, you will see
that application have some folders.

If you look at the above figure, you will four folders. The folders that are of our concern are
the source files folder and the header files folder.

What we are going to do is, we will have three files in our application. One is the main.cpp
which will be a class file. We have been using main.cpp in our previous programs. We will
have another file named Mathematics.cpp which will be another class file. And the third and
last file will be mathematics.h which will be a header file and will be used to communicate
between the main.cpp and Mathematics.cpp.

So, what we have are three files as follows.


main.cpp
mathematics.cpp
mathematics.h
Before, explanation of the code in above three files, follow these three steps.

1. Add main.cpp

This will be the file containing the main function as we have done previously. In all our
programs we have this file because this is the point where compiler enters the code.
Main.cpp will contain following code. If you do not previously have added this file to your
project solution, right click on the project name or the folder named source file in the solution
explorer and click on add new item. Add class from the list of items and name it main.cpp.
The file will be added to solution explorer. Paste the following code in main.cpp.
Code:

#include <iostream>
#include <string>
using namespace std;
#include "Mathematics.h"
int main() {
int num1, num2, result;
Mathematics maths;
cout <<"Enter the first number:";
cin>>num1;
cout<<"Enter the 2nd number:";
cin>>num2;
result = maths.add(num1, num2);
cout <<"\nThe result of adding two numbers is: "<<result<<endl;
result = maths.subtract(num1, num2);
cout <<"The result of subtracting two numbers is: "<<result<<endl;
result = maths.multiply(num1, num2);
cout <<"The result of multipltying two numbers is: "<<result<<endl;
result = maths.divide(num1, num2);
cout <<"The result of dividing two numbers is: "<<result<<endl;
}
For now, just be relaxed, I will be explaining this code later. Just copy this code into
main.cpp.

2. Add mathematics.cpp

This will be the class which contains the mathematical functionalities: Add, Subtract, Multiply
and divide. Remember, in some of our previous tutorials we have defined all these functions
in our main.cpp. Again, left click on the project name or the source files folder and add a
class. Name this class mathematics.cpp and add following code in that file.
Code:

#include "Mathematics.h"
int Mathematics::add(int num1, int num2) {
return Mathematics::result = num1 + num2;
}
int Mathematics::subtract(int num1, int num2) {
return Mathematics::result = num1 - num2;
}
int Mathematics::multiply(int num1, int num2) {
return Mathematics::result = num1 * num2;
}
int Mathematics::divide(int num1, int num2) {
return Mathematics::result = num1 / num2;
}
3. Add mathematics.h

This is the header file we talked in some of our last sections. This file acts as a bridge
between the main.cpp and mathematics.cpp. For now, just right click on Header files folder
in solution explorer and add new item. This time choose header file. Name the file
mathematics.h and add following code in the file.
Code:

#ifndef MATHEMATICS_H
#define MATHEMATICS_H
#include <iostream>
class Mathematics
{
int result;
public:
int add(int num1,int num2);
int subtract(int num1,int num2);
int multiply(int num1,int num2);
int divide(int num1,int num2);
};
#endif
After you add all the three files, your solution explorer should look like this:
Now come towards the files.

First we will discuss the Mathematics.h, the header file. The file starts with preprocessor
directives
Code:

#ifndef MATHEMATICS_H
#define MATHEMATICS_H
The above lines tell the compiler that it only has to create single version of the header file
that will be used to communicate with Mathematics.cpp. Next, we have simply import the
iostream class and have defined a class Mathematics in this header file. This class contains
one variable of type integer, named result and four function declarations. Note, we have set
the scope of the methods to public because we will access these methods from main.cpp.
Another very important thing to note here is that we have not provided any implementation
for the functions in header file. We have only declared the functions. In previous section we
discussed that header files are actually public interface to access the functionality from the
code in some other files, therefore; actual definition or implementation of these methods will
be in another file named mathematics.cpp.

Now come towards mathematics.cpp file. In this file we have provided definitions for the
functions we declared in the header file. An important thing to notice here is that we have
included mathematics.h file in this mathematics.cpp file on the top. This is because
mathematics.h file is glue and any file wanting to interact with other file through the interface
of mathematics.h has to import this file. You would have noted that instead of enclosing the
header file in <>, we have enclosed it in . This is due to the reason that to access the files
that are in the same directory is used. Whereas predefined class libraries and header files
are included in compilers include directory therefore in order to access those files we use
<>. You can find the files in the project folder. They will all be in same directory.

Another important thing worth noticing in mathematics.cpp is that we have not defined class
in this file. We have only defined functions. Therefore, in order to state that the function
belonged to the class Mathematics in header file, we prefix Mathematics followed by scope
resolution operator :: followed by the function or variable name as shown in
mathematics.cpp.

Now, come towards our main file. Here after including built-in class libraries, we have
included mathematics.h. This line of code let us access the Mathematics class and its
corresponding arithmetic functions and result variable in mathematics.cpp file.

Inside, the main method we declared a variable math of class Mathematics and have
performed mathematical operations using this file. You can see that here math variable will
act like variable of any built-in class.

This way we have successfully organized our mathematical program into two files. If we
want to further add any functionality, we will have to add it simply add it inside the
mathematics.cpp and will update the interface mathematics.h. Apart from using these
mathematical functionalities in main.cpp, we can use the code in this file in any other file by
simply including mathematics.h. When you compile the above code the output will be as
follows.

usmanmalik, Jan 22, 2014

SHARE #1

(You must log in or sign up to reply here.)

Share This Page


Sign up now!

MEMBERS ONLINE NOW


1. SHK
Total: 157 (members: 1, guests: 119, robots: 37)

NEW PROFILE POSTS

tutorsweb
Enroll online Free IT courses here:https://www.tutorsweb.com/courses
Thursday at 8:16 AM

RITESH KAKKAR Ashish Bisht


hello
Oct 4, 2016

RITESH KAKKAR Akshay singh


hello
Oct 4, 2016

Albee Aballa
can someone send me code for a phonebook application. PLease
Oct 3, 2016

Christer
Yeah!!!!!!!!
Sep 13, 2016

FORUM STATISTICS
DISCUSSIONS:

24,593

MESSAGES:

95,641

MEMBERS:

55,688

LATEST MEMBER:

Rugraj

HomeArticles > Programming > C++ >

HOME
ARTICLES
o Database
o Ethical hacking Tips
o Game Programming
o Engineering Concepts
o Internet Marketing
o Gadgets Review & Analysis
o Products Showcase
o ...
FORUMS
COMMUNITY
MEMBERS
NEWSLETTER
CONTACT US
HELP
HOME
TOP
RSS
User Contribution Licensed Under Creative Commons with Attribution Required. Site Design and Logo Copyright Go4Expert 2004 - 2016.

TERMS AND RULES


PRIVACY POLICY
Forum software by XenForo 2010-2016 XenForo Ltd.

Some XenForo functionality crafted by ThemeHouse.

You might also like