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. } In this case. objects and functions that are included within the namespace namespace myNamespace { int a. 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 ::. b. For example. to access the previous variables from outside myNamespace we can write: myNamespace::a myNamespace::b .

} namespace second { double var = 3. namespace first cout << second::var << endl. causing redefinition errors.1416.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. int var = 5. // namespaces int main () #include <iostream> { using namespace std. cout << first::var << endl. } } . { return 0.

cout << first::y << endl. cout << y << endl. int x = 5. int y = 10. namespace first using second::y.using The keyword using is used to introduce a name from a namespace into the current declarative region.7183. // using #include <iostream> int main () { using namespace std. double y = 2. using first::x.1416. } return 0. { cout << x << endl. namespace second { } double x = 3. . } cout << second::x << endl.

double y = 2. int y = 10.1416.7183. { cout << y << endl. } } .The keyword using can also be used as a directive to introduce an entire namespace: // using int main () #include <iostream> { using namespace std. namespace first cout << x << endl. cout << second::y << endl. int x = 5. namespace second { double x = 3. cout << second::x << endl. } return 0. using namespace first.

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. we could do something like the following example . Some times we might want to first use the objects of one namespace and then those of another one.

{ cout << x << endl. double x = 3. int main () { { namespace first using namespace first. } } return 0. int x = 5. { cout << x << endl.1416. } } { namespace second using namespace second.// using namespace example #include <iostream> using namespace std. } .

Namespace alias(Tagging namespaces) We can declare alternate names for existing namespaces according to the following format: namespace new_name = current_name. .

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

such as exiting the program . • 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.Handling Exception • If without handling.

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 .

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

  // Prints "Invalid customer age"           // More statements to handle an age error } catch ( SalaryError ) {          // Statements to handle a salary error } . string. and SalaryError } catch ( int ) {           // Statements to handle an int exception } catch ( string s ) {          cout << s << endl.Example of a try-catch Statement  try {           // Statements that process personnel data and may throw           // exceptions of type int.

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 .

} catch ( ErrType ) { } } void Func4() { Function call Normal return if ( error ) throw ErrType(). } Return from thrown  exception .Throwing an Exception to be Caught by the Calling Code void Func3() { try { Func4().

Practice: Dividing by ZERO Apply what you know: int Quotient(int numer. to avoid program //crash } . else //What to do?? do sth. int denom ) // The numerator // The denominator { if (denom != 0) return numer / denom.

//throw exception of class DivByZero return numer / denom.A Solution int Quotient(int numer. } . int denom ) // The numerator // The denominator { if (denom == 0) throw DivByZero().

denom) <<endl. } .A Solution // quotient.   // Denominator     //read in numerator        and denominator while(cin) {           try           {        cout << "Their quotient: "                << Quotient(numer. class DivByZero {}.cpp -- Quotient program   #include<iostream.           }      catch ( DivByZero )//exception handler      {       cout<<“Denominator can't be 0"<< endl.      }      // read in numerator and denominator     } return 0.h> #include <string.h> int Quotient( int.   // Numerator     int denom. int ). // Exception class int main() {     int numer.

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

num. .num==0) { throw "WRONG". } int div(number num2) { if(num2. } }.#include <iostream. public: void read() { cin>>num. } else return num/num2.h> class number { private: int num.

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