0
0
C++programming~5 mins

Throwing exceptions in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean to throw an exception in C++?
Throwing an exception means signaling that an error or unexpected event has occurred, by using the throw keyword followed by an object representing the error.
Click to reveal answer
beginner
How do you throw an exception with a message in C++?
You can throw an exception by writing <code>throw std::runtime_error("Error message");</code> where <code>std::runtime_error</code> is a standard exception class that takes a message.
Click to reveal answer
beginner
What happens after an exception is thrown?
The program stops normal execution and looks for a matching catch block to handle the exception. If none is found, the program usually terminates.
Click to reveal answer
intermediate
Can you throw any type of object as an exception in C++?
Yes, C++ allows throwing any type of object, but it is recommended to throw objects derived from std::exception for consistency and better error information.
Click to reveal answer
beginner
Write a simple C++ code snippet that throws and catches an exception.
<pre>#include &lt;iostream&gt;
#include &lt;stdexcept&gt;

try {
    throw std::runtime_error("Something went wrong");
} catch (const std::exception &amp;e) {
    std::cout << "Caught exception: " << e.what() << std::endl;
}</pre>
Click to reveal answer
Which keyword is used to throw an exception in C++?
Athrow
Bcatch
Ctry
Dexcept
What happens if an exception is thrown but not caught?
AProgram continues normally
BException is ignored
CException is automatically handled
DProgram terminates
Which of these is a recommended base class for exceptions in C++?
Astd::string
Bstd::exception
Cstd::vector
Dstd::cout
How do you catch an exception of type std::runtime_error?
Acatch (std::runtime_error &e)
Bcatch (int e)
Ccatch (std::string e)
Dcatch (float e)
Which block is used to write code that might throw an exception?
Afinally
Bthrow
Ctry
Dcatch
Explain how throwing and catching exceptions works in C++.
Think about how the program stops normal work and looks for a handler.
You got /5 concepts.
    Write a simple example of throwing an exception with a message and catching it.
    Use std::runtime_error and std::exception for your example.
    You got /4 concepts.