C++ Introduction to Programming It is short and simple practice. Please solve #6
ID: 3774280 • Letter: C
Question
C++ Introduction to Programming
It is short and simple practice.
Please solve #6, 7, 8, 9, 10
#include<iostream>
...
Classes: members and methods
Classes, continued: access specifiers and constructors
Classes for object oriented design
Recursion
Multi-file projects and header files
Exceptions, tests, and assertions
Assertions, Advanced Input/Output
Operator Overloading; Inheritance and Abstract data types
Explanation / Answer
//6.
#include <iostream>
using namespace std;
void f()
{
cout<<"Hello"<<endl;
throw 5;
cout<<"Goodbye!"<<endl;
}
int main()
{
cout<<"Greetings!"<<endl;
try
{
f();
}
catch(int e)
{
cout << "Whoops!" << endl;
}
cout << "Farewell!" << endl;
return 0;
}
OUTPUT:
Greetings!
Hello
Whoops!
Farewell!
//7.
#include <iostream>
#include<stdexcept>
using namespace std;
void f();
void g();
int main()
{
cout<<"Greetings!"<<endl;
try
{
f();
}
catch(runtime_error& e)
{
cout << "Tragedy strikes!" << endl;
}
return 0;
}
void f()
{
cout<<"Here we go..."<<endl;
try {
g();
}
catch(exception& e)
{
cout<<"Oh noes!"<<endl;
}
}
void g()
{
cout<<"Working..."<<endl;
throw runtime_error{"Yikes!"};
cout<<"Done!"<<endl;
}
OUTPUT :
Greetings!
Here we go...
Working...
Oh noes!
//8.
a. std::range_error This is occured when you try to store a value which is out of range.
b. std::runtime_error An exception that theoretically can not be detected by reading the code.
c. std::invalid_argument This is thrown due to invalid arguments.
//9.
#include <iostream>
#include<stdexcept>
using namespace std;
void f();
int main()
{
try
{
f();
}
catch(runtime_error& e)
{
cout << "runtime_error!" << endl;
}
catch(out_of_range& e)
{
cout << "out_of_range!" << endl;
}
return 0;
}
void f()
{
int x;
cin>>x;
if(x<0)
throw out_of_range{"WHAT"};
else if(x==0)
throw runtime_error{"WHAT"};
else
cout<<x;
}
//10.
#include <iostream>
#include<stdexcept>
using namespace std;
int main()
{
try
{
void f();
void g();
void h();
}
catch(exception& e)
{
cout<<"Error!"
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.