name spaces
DESCRIPTION
Namespaces 2 in c++TRANSCRIPT
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
#include <iostream>
using namespace std;
namespace first
{
int var = 5;
}
namespace second
{
double var = 3.1416;
}
int main ()
{
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
using
The keyword using is used to introduce a name from a namespace into the current declarative region.
// using
#include <iostream>
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3.1416;
double y = 2.7183;
}
int main ()
{
using first::x;
using second::y;
cout << x << endl;
cout << y << endl;
cout << first::y << endl;
cout << second::x << endl;
return 0;
}
The keyword using can also be used as a directive to introduce an entire namespace:
// using
#include <iostream>
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3.1416;
double y = 2.7183;
}
int main ()
{
using namespace first;
cout << x << endl;
cout << y << endl;
cout << second::x << endl;
cout << second::y << endl;
return 0;
}
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;
namespace first
{
int x = 5;
}
namespace second
{
double x = 3.1416;
}
int main ()
{
{
using namespace first;
cout << x << endl;
}
{
using namespace second;
cout << x << endl;
}
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
try Blockcatch (FormalParameter) Blockcatch (FormalParameter)
TryCatchStatement
How one part of the program catches and processes the exception that another part of the program throws.
FormalParameter
DataType VariableName
…
Example of a try-catch Statement
try{ // Statements that process personnel data and may throw // exceptions of type int, string, and SalaryError}catch ( int ){ // Statements to handle an int exception}catch ( string s ){ cout << s << endl; // Prints "Invalid customer age" // More statements to handle an age error}catch ( SalaryError ){ // Statements to handle a salary error}
Execution of try-catch
No statements throw
an exception
Statement following entire try-catch
statement
A statement throws
an exception
Exception Handler
Statements to deal with exception are executed
Control moves directly to exception handler
Throwing an Exception to be Caught by the Calling Code
void Func4() { if ( error ) throw ErrType(); }
Normalreturn
void Func3(){ try { Func4(); } catch ( ErrType ) { } }
Functioncall
Return fromthrown exception
Practice: Dividing by ZERO
Apply what you know:
int Quotient(int numer, // The numerator
int denom ) // The denominator
{
if (denom != 0)
return numer / denom;
else
//What to do?? do sth. to avoid program //crash
}
int Quotient(int numer, // The numerator
int denom ) // The denominator
{
if (denom == 0)
throw DivByZero();
//throw exception of class DivByZero
return numer / denom;
}
A Solution
A Solution
// quotient.cpp -- Quotient program
#include<iostream.h>#include <string.h>
int Quotient( int, int );
class DivByZero {}; // Exception class
int main()
{
int numer; // Numerator
int denom; // Denominator
//read in numerator
and denominator
while(cin)
{ try { cout << "Their quotient: "
<< Quotient(numer,denom) <<endl;
} catch ( DivByZero )//exception handler
{
cout<<“Denominator can't be 0"<< endl;
}
// read in numerator and denominator }
return 0;
}
#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;
}