Introduction to programming in c 6 The following function th
Introduction to programming in c++
6. The following function throws an exception consisting of an
int, 5:
~~~~
void f() {
std::cout << \"Hello\" << std::endl;
throw 5;
std::cout << \"Goodbye!\" << std::endl;
}
~~~~
Modify the following main() so that it catches the exception and
prints \"Whoops!\" when it occurs (and then continues to print
\"Farewell\", as it would if the exception had not occured):
~~~~
// MODIFY THIS PROGRAM
#include <iostream>
int main() {
std::cout << \"Greetings!\" << std::endl;
f();
std::cout << \"Farewell!\" << std::endl;
return 0;
}
3. Here is a set of namespaces containing several functions.
~~~~
namespace A {
int f() { return 0; }
int g() { return 1; }
}
namespace B {
void x() {}
void y() {}
namespace C {
int h() { return 2; }
void z() {}
}
}
~~~~
Fix the following code so that it executes the functions f(), g(),
h(), x(), y(), and z(), in that order:
~~~~
int a = f(), b = g();
float c = h();
x();
y();
z();
~~~~
Solution
#include <iostream>
int main() {
std::cout << \"Greetings!\" << std::endl;
try{
c=f();
catch(int e))
{
if(e==5) {
std::cout<<\"Whoops\";
}
else
{
std::cout << \"Farewell!\" << std::endl;
}
}
return 0;
}
}
Well nameSpace is a concept of calling a function,or method within that Scope...we have predefined namespace as Std (Standard) .To avoid writing namespace to every Statement we do
using namespace Std; //std nameof namespace and namespace, using are keywords defined in C++
using namespace u can use the same function name in multiple namespaces
since f() and g() belongs to namespace A we call them as A::f() and similarly A::g()
so the statements int a=A::f(), b=A::g();
Similarly, h() is in the namespace of both B and C and this type is called as nested namespace , we will call the function as B::C::h()
so now the statement float c=B::C::h()
so ,x(),y(),z() are within the namespace of B so,
B::x()
B::y()
B::C::z()


