Unit 6: Handling Exceptions, Templates and STL - Practice Quiz

CAP455 — Object Oriented Programming Using C++ 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is the main purpose of exception handling in C++?

Basics of exception handling Easy
A. To create header files
B. To handle runtime errors
C. To declare data members
D. To overload operators

2 Which C++ feature is commonly used to handle exceptional conditions?

Basics of exception handling Easy
A. for loops
B. try-catch blocks
C. switch statements
D. if-else blocks

3 Which block contains code that may generate an exception?

Exception handling mechanism Easy
A. catch block
B. finally block
C. try block
D. default block

4 What happens when an exception is thrown in a try block?

Exception handling mechanism Easy
A. The compiler deletes the block
B. A matching handler is searched
C. The exception becomes a comment
D. The program always continues normally

5 Which keyword is used to explicitly generate an exception in C++?

Throwing exception mechanism Easy
A. throw
B. exception
C. raise
D. throws

6 Which statement correctly throws the integer value ?

Throwing exception mechanism Easy
A. throw 5;
B. try 5;
C. catch 5;
D. raise 5;

7 Which keyword introduces an exception handler?

Catching exception mechanism Easy
A. rescue
B. handle
C. error
D. catch

8 What does catch(...) match in C++?

Catching exception mechanism Easy
A. Any exception type
B. Only string exceptions
C. Only standard exceptions
D. Only integer exceptions

9 Which statement re-throws the currently handled exception?

Re-throwing an exception Easy
A. throw();
B. throw;
C. catch;
D. rethrow;

10 Why might a function re-throw an exception?

Re-throwing an exception Easy
A. To prevent every handler from running
B. To convert it into a loop
C. To let another handler process it
D. To remove all program errors

11 What is the main purpose of a function template?

Function template Easy
A. To reserve permanent memory
B. To define only integer functions
C. To prevent function overloading
D. To write type-independent functions

12 Which keyword commonly declares a template parameter in C++?

Function template Easy
A. templateType
B. typename
C. parameter
D. generic

13 What does a class template provide?

Class template Easy
A. A method for handling exceptions
B. A fixed class for one object
C. A replacement for constructors
D. A blueprint for generic classes

14 Which syntax creates an object of a class template using int as its type?

Class template Easy
A. Box<int> b;
B. Box(int) b;
C. Box b<int>();
D. template Box b<int>;

15 What can a class template be used as in inheritance?

Class template and inheritance Easy
A. Only a namespace
B. Only a preprocessor macro
C. Only a local variable
D. A base class

16 What is the Standard Template Library mainly known for providing?

Introduction and importance of Standard Template Library (STL) Easy
A. Reusable containers and algorithms
B. Database connection protocols
C. Operating system drivers
D. Graphical user interfaces

17 What is an STL container used for?

Containers Easy
A. Catching only exceptions
B. Storing collections of objects
C. Declaring namespaces
D. Compiling source code

18 Which STL component provides operations such as sorting and searching?

Algorithms Easy
A. Namespaces
B. Algorithms
C. Preprocessors
D. Constructors

19 What is the main role of an STL iterator?

Iterators Easy
A. To allocate class objects
B. To define template parameters
C. To traverse container elements
D. To handle compiler warnings

20 Which statement best describes an STL vector?

Vector container Easy
A. A dynamically sized array
B. A template declaration keyword
C. A linked error handler
D. A fixed-size function

21 What happens to local automatic objects when an exception leaves the function in which those objects were created?

Basics of exception handling Medium
A. Their constructors are called again by the handler
B. Their destructors run only if the exception is caught locally
C. Their memory remains allocated until program termination
D. Their destructors are called during stack unwinding

22 Given class Derived : public Base {};, which ordering of handlers correctly allows a Derived exception to receive specialized handling?

Exception handling mechanism Medium
A. catch(...) before catch(Derived& d)
B. catch(Base& b) before catch(Derived& d)
C. catch(Base b) followed by catch(Base& b)
D. catch(Derived& d) before catch(Base& b)

23 Consider double x = -2.0; if (x < 0) throw x;. Which handler directly matches the type of the thrown exception?

Throwing exception mechanism Medium
A. catch(double value)
B. catch(float value)
C. catch(long value)
D. catch(int value)

24 Why is catch(const std::exception& e) generally preferred to catch(std::exception e)?

Catching exception mechanism Medium
A. It converts every exception into std::exception
B. It automatically retries the failed statement
C. It prevents stack unwinding from taking place
D. It avoids slicing and unnecessary copying

25 Inside a catch block, which statement rethrows the currently handled exception while preserving its original exception object?

Re-throwing an exception Medium
A. throw;
B. catch;
C. return;
D. throw e;

26 For template<class T> T maximum(T a, T b);, what happens when maximum(4, 6.5) is called without explicit template arguments?

Function template Medium
A. Template argument deduction fails because the arguments imply different types
B. T is deduced as double through automatic numeric promotion
C. Two specializations are generated and their results are compared
D. T is deduced as int because the first argument determines it

27 Given template<class T> T square(T x) { return x * x; }, what is the type of the result of square<double>(3)?

Function template Medium
A. float
B. double
C. int
D. long

28 A class template Counter<T> contains static int count;. What is true of Counter<int>::count and Counter<double>::count?

Class template Medium
A. They refer to one shared static member
B. They are separate static members
C. Both members must always contain equal values
D. Only the first specialization has the member

29 For template<class T> class Box { T value; };, which declaration creates an object whose value member has type std::string?

Class template Medium
A. Box<string()> item;
B. Box item<std::string>;
C. Box<std::string> item;
D. template Box<std::string> item;

30 Suppose template<class T> class Base {};. Which declaration correctly defines a class template Derived<T> that publicly inherits from Base<T>?

Class template and inheritance Medium
A. class Derived<T> : public Base<T> {};
B. template<class T> class Derived : public Base<T> {};
C. template<class T> class Derived : public Base {};
D. template<class T> class Derived : Base<class T> {};

31 Which STL design feature most directly allows one algorithm such as std::find to work with several different container types?

Introduction and importance of Standard Template Library (STL) Medium
A. Algorithms operate on iterator ranges
B. Containers store every element as void*
C. Containers all inherit from one base class
D. Algorithms access container fields directly

32 A program needs unique keys maintained in sorted order with efficient key-based lookup. Which standard container best matches these requirements?

Containers Medium
A. std::set
B. std::vector
C. std::list
D. std::multiset

33 Which call correctly sorts every element of std::vector<int> values in ascending order?

Algorithms Medium
A. std::sort(values.begin(), values.end() - 1);
B. std::sort(values.begin(), values.end());
C. std::sort(values.end(), values.begin());
D. std::sort(values.front(), values.back());

34 Why must v.end() not be dereferenced for a nonempty vector v?

Iterators Medium
A. It becomes valid only after calling v.back()
B. It denotes the final element but only for writing
C. It stores the vector's current capacity value
D. It denotes the position just after the last element

35 An iterator points to an element of a vector. A later push_back causes the vector to reallocate its storage. What happens to the old iterator?

Vector container Medium
A. It is converted automatically into a const iterator
B. It remains valid but points to the next element
C. It remains valid if the inserted value has the same type
D. It is invalidated by the reallocation

36 After std::vector<int> v; v.reserve(20);, which statement is guaranteed before additional elements are inserted?

Vector container Medium
A. v.size() is 20 and all elements contain 0
B. v.size() is 0 and v.capacity() is at least 20
C. v.size() is 0 and v.capacity() remains 0
D. v.size() is 20 and v.capacity() is exactly 20

37 What is the main effect of destination.splice(destination.end(), source) for two compatible std::list<int> objects?

List container Medium
A. It copies all values while leaving source unchanged
B. It transfers all nodes from source to destination
C. It swaps only the final nodes of the two lists
D. It merges both lists and automatically sorts the result

38 Why is std::sort(items.begin(), items.end()) unsuitable when items is a std::list<int>?

List container Medium
A. std::sort accepts only vector iterators
B. std::sort cannot compare integer elements
C. std::sort requires contiguous element storage
D. std::sort requires random-access iterators

39 Function f() throws an exception, g() calls f() without a matching handler, and main() calls g() inside a matching try block. Where is the exception handled?

Exception handling mechanism Medium
A. Automatically at the end of f()
B. Nowhere because handlers cannot cross function calls
C. In the matching handler in main()
D. Automatically at the end of g()

40 Where should a catch(...) handler be placed when it follows typed handlers for the same try block?

Catching exception mechanism Medium
A. After all typed handlers
B. Before all typed handlers
C. Between try and the first handler
D. Inside the first typed handler

41 Consider the following program:

CPP
struct Guard {
    ~Guard() { throw 2; }
};

int main() {
    try {
        Guard g;
        throw 1;
    } catch (...) {
        std::cout << "caught";
    }
}



Assuming the default exception specifications generated by modern C++, what is the program's outcome?

Basics of exception handling Hard
A. It prints caught after discarding the exception thrown by the destructor.
B. It has undefined behavior because destructors cannot contain a throw expression.
C. It invokes std::terminate when the destructor throws during stack unwinding.
D. It catches the integer 2 because the destructor's exception replaces integer 1.

42 What is printed by the following program?

CPP
struct X {
    char id;
    ~X() { std::cout << id << ' '; }
};

int main() {
    try {
        X a{'A'};
        try {
            X b{'B'};
            throw 7;
        } catch (double) {
            std::cout << "D ";
        }
    } catch (int) {
        std::cout << "C";
    }
}

Exception handling mechanism Hard
A. B D A C
B. B A C
C. D B A C
D. A B C

43 What does this code print?

CPP
struct Base {
    virtual const char* name() const { return "Base"; }
    virtual ~Base() = default;
};
struct Derived : Base {
    const char* name() const override { return "Derived"; }
};

int main() {
    try {
        throw Derived{};
    } catch (Base b) {
        std::cout << b.name();
    }
}

Throwing exception mechanism Hard
A. The program is ill-formed because exceptions cannot be caught by value.
B. Nothing, because a Derived object cannot match a Base handler.
C. Derived, because virtual dispatch preserves the thrown object's type.
D. Base, because the handler parameter slices the caught object.

44 Given the handlers below, which one handles throw Derived{};?

CPP
struct Base { virtual ~Base() = default; };
struct Derived : Base {};

try {
    throw Derived{};
} catch (Base& e) {
    std::cout << "base";
} catch (Derived& e) {
    std::cout << "derived";
} catch (...) {
    std::cout << "other";
}

Catching exception mechanism Hard
A. The program is ill-formed because related exception types cannot share a try block.
B. The catch (...) handler handles it because polymorphic objects require ellipsis.
C. The Derived& handler handles it because exact matches always take priority.
D. The Base& handler handles it because handlers are tested in source order.

45 Assume Derived publicly inherits from polymorphic Base. Compare these two handlers:

CPP
void g() {
    try { throw Derived{}; }
    catch (Base& e) { throw e; }
}

void h() {
    try { throw Derived{}; }
    catch (Base& e) { throw; }
}



If each function is called inside handlers for Derived& followed by Base&, which pair is selected?

Re-throwing an exception Hard
A. g: Derived&; h: Base&
B. g: Base&; h: Base&
C. g: Base&; h: Derived&
D. g: Derived&; h: Derived&

46 Given the function template below, what happens at the marked call?

CPP
template<class T>
T combine(T a, T b) { return a + b; }

auto x = combine(1, 2.5); // marked call

Function template Hard
A. The call is ambiguous between implicit int and double instantiations.
B. T is deduced as double, and x becomes 3.5.
C. T is deduced as int, and x becomes 3.
D. Deduction fails because the two arguments imply different types for T.

47 For the forwarding-reference template below, what are the deduced types of T?

CPP
template<class T>
void inspect(T&& value);

int n = 0;
inspect(n);  // call 1
inspect(0);  // call 2

Function template Hard
A. Call 1: int; call 2: int&&
B. Call 1: int&; call 2: int&&
C. Call 1: const int&; call 2: int
D. Call 1: int&; call 2: int

48 What does the call f(p) print?

CPP
template<class T>
void f(T) { std::cout << "primary"; }

template<class T>
void f(T*) { std::cout << "pointer"; }

template<>
void f<int*>(int*) { std::cout << "special"; }

int* p = nullptr;
f(p);

Function template Hard
A. primary, because explicit specializations disable template ordering.
B. pointer, because overload resolution selects the pointer primary template.
C. The call is ambiguous between the pointer overload and the specialization.
D. special, because an explicit specialization always wins overload resolution.

49 Which replacement makes the following template well-formed?

CPP
template<class T>
struct Wrapper {
    using Container = T;

    void process() {
        /* replacement */ item{};
    }
};



The replacement must declare item using the nested type Container::value_type.

Class template Hard
A. template Container::value_type item`
B. class Container::value_type item`
C. Container::value_type item`
D. typename Container::value_type item`

50 What is printed by this class-template partial specialization?

CPP
template<class T>
struct Kind {
    static constexpr const char* name = "ordinary";
};

template<class T>
struct Kind<T*> {
    static constexpr const char* name = "pointer";
};

std::cout << Kind<const int*>::name;

Class template Hard
A. pointer, with T deduced as const int.
B. ordinary, because partial specializations ignore cv-qualified types.
C. The instantiation is ambiguous because const may qualify either level.
D. ordinary, because const int* is not exactly T*.

51 Why does return value; fail in the template below, and which replacement fixes it?

CPP
template<class T>
struct Base {
    int value = 42;
};

template<class T>
struct Derived : Base<T> {
    int get() const { return value; }
};

Class template and inheritance Hard
A. The member is private; replace it with Base<T>::get(value).
B. The member is static; replace it with Base<T>::value.
C. The name is ambiguous; replace it with Derived::value.
D. The base is dependent; replace it with this->value.

52 What mechanism causes Algorithm<Fast>::run() to call Fast::execute()?

CPP
template<class Derived>
struct Algorithm {
    void run() {
        static_cast<Derived*>(this)->execute();
    }
};

struct Fast : Algorithm<Fast> {
    void execute() { std::cout << "fast"; }
};

Class template and inheritance Hard
A. Static polymorphism through the curiously recurring template pattern
B. Runtime virtual dispatch through a generated virtual table
C. Argument-dependent lookup through the Fast class namespace
D. Function-template specialization performed when run is called

53 Which design property most directly allows one STL algorithm such as std::find to operate on arrays, vectors, and lists without those containers sharing a common base class?

Introduction and importance of Standard Template Library (STL) Hard
A. Containers inherit from a hidden standard polymorphic container abstraction.
B. Algorithms operate through iterator interfaces and required iterator operations.
C. Containers are converted into a universal internal sequence before each algorithm.
D. Algorithms use runtime reflection to discover each container's member functions.

54 An insertion into a std::unordered_map triggers a rehash but does not erase any element. Which statement correctly describes invalidation?

Containers Hard
A. Only the past-the-end iterator is invalidated; element iterators remain valid.
B. All iterators, references, and pointers to stored elements are invalidated.
C. All iterators are invalidated, but references and pointers to elements remain valid.
D. All references are invalidated, but iterators and pointers remain valid.

55 After executing the code below, which property is guaranteed?

CPP
std::vector<int> v{1, 2, 1, 3, 1};
auto new_end = std::remove(v.begin(), v.end(), 1);

Algorithms Hard
A. v.size() is 5, and the vector's complete contents remain unchanged.
B. v.size() is 5, and [v.begin(), new_end) equals {2, 3}.
C. v.size() is 2, and the complete vector equals {2, 3}.
D. v.size() is 3, and [new_end, v.end()) contains only 1s.

56 What is the logical range produced by std::unique in this example?

CPP
std::vector<int> v{1, 2, 1, 1, 2};
auto e = std::unique(v.begin(), v.end());

Algorithms Hard
A. [v.begin(), e) is {1, 2, 1}, because the final repeated value is discarded.
B. [v.begin(), e) is {1, 2}, because all duplicate values are removed.
C. [v.begin(), e) is {1, 2, 1, 2}, because only adjacent duplicates collapse.
D. [v.begin(), e) is {1, 2, 2}, because equal values become adjacent first.

57 Let v be a std::vector<int> and l a std::list<int>, each containing elements. What are the standard complexity characteristics of std::distance(v.begin(), v.end()) and std::distance(l.begin(), l.end())?

Iterators Hard
A. Both are linear time because std::distance increments every iterator.
B. The vector distance is constant time; the list distance is linear time.
C. The vector distance is linear time; the list distance is constant time.
D. Both are constant time because every container stores its size.

58 Assume sufficient memory is available. What is guaranteed by this code?

CPP
std::vector<int> v;
v.reserve(4);
v.push_back(10);
int* p = &v[0];
v.push_back(20);
std::cout << *p;

Vector container Hard
A. It prints 10 because the second insertion cannot exceed the reserved capacity.
B. Dereferencing p is undefined because every push_back invalidates pointers.
C. It prints 20 because push_back may relocate the first element in place.
D. The result is unspecified because reserve provides only a size guarantee.

59 A std::vector<int> has spare capacity, and an element is inserted into its middle without reallocation. Which iterators are invalidated?

Vector container Hard
A. Only the iterator designating the newly inserted element is invalidated.
B. Only the old past-the-end iterator is invalidated; all element iterators remain valid.
C. All iterators are invalidated even though no reallocation occurs.
D. Iterators at or after the insertion point are invalidated; earlier ones remain valid.

60 What is true after executing this code?

CPP
std::list<int> a{1, 2};
std::list<int> b{3, 4};
auto it = std::next(b.begin()); // points to 4
a.splice(std::next(a.begin()), b, it);

List container Hard
A. a is {4, 1, 2}, b is {3}, and all iterators into both lists are invalidated.
B. a is {1, 2, 4}, b is {3}, and it is invalidated by the transfer.
C. a is {1, 4, 2}, b is {3}, and it still refers to 4 in a.
D. a is {1, 4, 2}, b is {3}, and it still belongs to b.