Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 23

Namespaces

Namespaces
Allow to group entities like classes, objects and functions
under a name.
This way the global scope can be divided in "sub-scopes",
each one with its own name.
The format of namespaces is:
Namespace identifier
{
entities
}

Here identifier is any valid identifier and entities is the set of


classes, objects and functions that are included within the
namespace
namespace myNamespace
{
int a, b;
}
In this case, the variables a and b are normal variables declared within a
namespace called myNamespace. In order to access these variables from
outside the myNamespace namespace we have to use the scope
operator ::.
For example, to access the previous variables from outside
myNamespace we can write:
myNamespace::a
myNamespace::b

The functionality of namespaces is especially useful in the


case that there is a possibility that a global object or
function uses the same identifier as another one, causing
redefinition errors.
// namespaces

int main ()

#include <iostream>

using namespace std;

cout << first::var << endl;

namespace first

cout << second::var << endl;

return 0;
int var = 5;

}
namespace second
{
double var = 3.1416;
}

using
The keyword using is used to introduce a name from a namespace into the
current declarative region.
// using
#include <iostream>

int main ()
{

using namespace std;

using first::x;

namespace first

using second::y;

cout << x << endl;


int x = 5;

cout << y << endl;

int y = 10;

cout << first::y << endl;

cout << second::x << endl;

namespace second
{

}
double x = 3.1416;
double y = 2.7183;

return 0;

The keyword using can also be used as a directive to introduce


an entire namespace:
// using

int main ()

#include <iostream>

using namespace std;

using namespace first;

namespace first

cout << x << endl;

cout << y << endl;


int x = 5;

cout << second::x << endl;

int y = 10;

cout << second::y << endl;

return 0;

namespace second
{
double x = 3.1416;
double y = 2.7183;
}

Using and using namespace have validity only in the


same block in which they are stated or in the entire code if they
are used directly in the global scope.
Some times we might want to first use the objects of one
namespace and then those of another one, we could do
something like the following example

// using namespace example


#include <iostream>
using namespace std;

int main ()
{
{

namespace first

using namespace first;

cout << x << endl;

int x = 5;

namespace second

using namespace second;

cout << x << endl;

double x = 3.1416;

return 0;
}

Namespace alias(Tagging namespaces)


We can declare alternate names for existing
namespaces according to the following format:
namespace new_name = current_name;

Exception
An exception is a unusual, often
unpredictable event, detectable by
software or hardware, that requires
special processing occurring at
runtime
In C++, a variable or class object that
represents an exceptional event.

Handling Exception
If without handling,
Program crashes
Falls into unknown state
An exception handler is a section of
program code that is designed to execute
when a particular exception occurs
Resolve the exception
Lead to known state, such as exiting
the program

Standard Exceptions

Exceptions Thrown by the Language

new

Exceptions Thrown by Standard


Library Routines
Exceptions Thrown by user code,
using throw statement

The throw Statement


Throw: to signal the fact that
an exception has occurred; also
called raise
ThrowStatement

throw Expression

The try-catch Statement


How one part of the program catches and processes
the exception that another part of the program throws.
TryCatchStatement
try
Block
catch (FormalParameter)
Block
catch (FormalParameter)
FormalParameter
DataType VariableName

Example of a try-catch Statement


try
{
//Statementsthatprocesspersonneldataandmaythrow
//exceptionsoftypeint,string,andSalaryError
}
catch(int)
{
//Statementstohandleanintexception
}
catch(strings)
{
cout<<s<<endl;//Prints"Invalidcustomerage"
//Morestatementstohandleanageerror
}
catch(SalaryError)
{
//Statementstohandleasalaryerror
}

Execution of try-catch
A
statement throws
an exception
Control moves
directly to exception
handler

No
statements throw
an exception

Exception
Handler

Statements to deal with exception are executed

Statement
following entire try-catch
statement

Throwing an Exception to be
Caught by the Calling Code
void Func3()
{
try
{
Func4();
}
catch ( ErrType )
{
}
}

void Func4()
{

Function
call
Normal
return

if ( error )
throw ErrType();
}

Returnfrom
thrown
exception

Practice: Dividing by ZERO


Apply what you know:
int Quotient(int numer,
int denom )

// The numerator
// The denominator

{
if (denom != 0)
return numer / denom;
else
//What to do?? do sth. to avoid program
//crash
}

A Solution
int Quotient(int numer,
int denom )

// The numerator
// The denominator

{
if (denom == 0)
throw DivByZero();
//throw exception of class DivByZero
return numer / denom;
}

A Solution
//quotient.cpp--Quotientprogram

#include<iostream.h>
#include<string.h>
intQuotient(int,int);
classDivByZero{};//Exceptionclass
intmain()
{
intnumer;//Numerator
intdenom;//Denominator
//readinnumerator
anddenominator

while(cin)
{

try

{
cout<<"Theirquotient:"
<<Quotient(numer,denom)<<endl;

}
catch(DivByZero)//exceptionhandler
{
cout<<Denominatorcan'tbe0"<<endl;
}
//readinnumeratoranddenominator
}
return0;
}

#include <iostream.h>
int main()
{
char * buf;
try
{
buf = new char [51200000000];
if(buf ==0)
throw "Memory Allocation failure!";
cout<<"Successful";
}
catch (char *str)
{
cout<<"Exception raised:"<< str<<"\n";
}
return 0;
}

#include <iostream.h>
class number
{
private:
int num;
public:
void read()
{
cin>>num;
}

int div(number num2)


{
if(num2.num==0)
{
throw "WRONG";
}
else
return num/num2.num;
}
};

void main()
{
number n1,n2;
int result=0;
cout<<"Enter number1-";
n1.read();
cout<<"Enter number2-";
n2.read();
try
{
cout<<"\nTrying the division...";
result=n1.div(n2);
cout<<"\nsuccessful\n";
}
catch(char *p)
{
cout<<p<<"\nfailed\n";
cout<<"Exception :divide by 0\n";
}
cout<<"num1/num2 "<<result;
}

You might also like