Bird
Raised Fist0
C++programming~20 mins

Throwing exceptions in C++ - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Exception Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this C++ code with exception throwing?

Consider the following C++ program. What will it print when run?

C++
#include <iostream>
#include <stdexcept>

int main() {
    try {
        throw std::runtime_error("Error happened");
        std::cout << "No error" << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Caught: " << e.what() << std::endl;
    }
    return 0;
}
ACaught: Error happened
BNo error
CCaught: std::runtime_error
DProgram crashes with uncaught exception
Attempts:
2 left
πŸ’‘ Hint

Remember that throwing an exception transfers control to the matching catch block.

❓ Predict Output
intermediate
2:00remaining
What error does this code produce?

What happens when this C++ code runs?

C++
#include <iostream>
#include <string>

void f() {
    throw 42;
}

int main() {
    try {
        f();
    } catch (const std::string& e) {
        std::cout << "Caught string: " << e << std::endl;
    }
    return 0;
}
ANo output, program runs normally
BCaught string: 42
CCompilation error due to catch type mismatch
DProgram terminates with uncaught exception
Attempts:
2 left
πŸ’‘ Hint

Check if the catch block matches the thrown exception type.

πŸ”§ Debug
advanced
2:00remaining
Why does this code fail to catch the exception?

Identify the reason the exception is not caught in this C++ code snippet.

C++
#include <iostream>
#include <stdexcept>

int main() {
    try {
        throw "Error";
    } catch (const std::exception& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }
    return 0;
}
ACannot catch a const char* with std::exception reference
BMissing semicolon after throw statement
Cstd::exception does not have what() method
DThrowing string literals is not allowed
Attempts:
2 left
πŸ’‘ Hint

Think about the type of the thrown object and the catch parameter type.

❓ Predict Output
advanced
2:00remaining
What is the output of nested try-catch with rethrow?

What will this C++ program print?

C++
#include <iostream>
#include <stdexcept>

int main() {
    try {
        try {
            throw std::logic_error("Logic error");
        } catch (const std::logic_error& e) {
            std::cout << "Inner catch: " << e.what() << std::endl;
            throw;  // rethrow
        }
    } catch (const std::exception& e) {
        std::cout << "Outer catch: " << e.what() << std::endl;
    }
    return 0;
}
AOuter catch: Logic error
BInner catch: Logic error
C
Inner catch: Logic error
Outer catch: Logic error
DProgram crashes with uncaught exception
Attempts:
2 left
πŸ’‘ Hint

Remember that throw; rethrows the current exception to the outer catch block.

🧠 Conceptual
expert
2:00remaining
Which option correctly describes exception object slicing in C++?

Consider throwing a derived class exception object but catching by value as a base class. What happens?

AThe catch block receives the full derived class object with all info intact
BThe caught exception object is sliced to base class, losing derived class info
CThe program crashes due to slicing at runtime
DCatching by value is not allowed in C++
Attempts:
2 left
πŸ’‘ Hint

Think about what happens when an object is copied by value from a derived to a base class type.

Practice

(1/5)
1. What does the throw keyword do in C++?
easy
A. It defines a new function.
B. It catches an exception.
C. It signals an error by raising an exception.
D. It declares a variable.

Solution

  1. Step 1: Understand the purpose of throw

    The throw keyword is used to signal that an error or exceptional condition has occurred in the program.
  2. Step 2: Differentiate from other keywords

    throw does not catch exceptions (that's catch), nor does it define functions or declare variables.
  3. Final Answer:

    It signals an error by raising an exception. -> Option C
  4. Quick Check:

    throw = signal error [OK]
Hint: Remember: throw means "raise an error" [OK]
Common Mistakes:
  • Confusing throw with catch
  • Thinking throw declares variables
  • Assuming throw defines functions
2. Which of the following is the correct syntax to throw an integer exception with value 10?
easy
A. throw int 10;
B. throw(int 10);
C. throw new int(10);
D. throw 10;

Solution

  1. Step 1: Recall correct throw syntax

    In C++, to throw an exception, you use throw followed by the value or object, without parentheses or type keywords.
  2. Step 2: Analyze each option

    throw 10; uses throw 10; which is correct. throw(int 10); incorrectly declares a type inside parentheses, invalid syntax. throw int 10; incorrectly adds type keyword. throw new int(10); throws a pointer, which is allowed but not the simplest form here.
  3. Final Answer:

    throw 10; -> Option D
  4. Quick Check:

    Simple throw syntax = throw value; [OK]
Hint: Use throw followed directly by value, no parentheses [OK]
Common Mistakes:
  • Adding parentheses after throw
  • Including type keyword with throw
  • Throwing pointers when not needed
3. What will be the output of the following code?
try {
  throw "Error occurred";
} catch (const char* msg) {
  std::cout << msg << std::endl;
}
medium
A. Error occurred
B. Runtime crash
C. No output
D. Compilation error

Solution

  1. Step 1: Understand the throw and catch block

    The code throws a string literal "Error occurred" and catches it as a const char* pointer.
  2. Step 2: Check the catch block output

    The catch block prints the caught message using std::cout, so it will output the string "Error occurred" followed by a newline.
  3. Final Answer:

    Error occurred -> Option A
  4. Quick Check:

    Thrown string caught and printed = "Error occurred" [OK]
Hint: Thrown string literals caught as const char* print directly [OK]
Common Mistakes:
  • Expecting compilation error due to throw
  • Thinking catch won't match string literal
  • Assuming no output without explicit return
4. Identify the error in this code snippet:
try {
  throw 5;
} catch (int e) {
  std::cout << "Caught: " << e << std::endl;
} catch (...) {
  std::cout << "Unknown exception" << std::endl;
}
medium
A. No error, code is correct
B. Multiple catch blocks for same exception type
C. Catch block missing parameter type
D. Throwing wrong data type

Solution

  1. Step 1: Analyze the try and catch blocks

    The code throws an integer 5, which is caught by the first catch block for int. The second catch block is a catch-all for any other exceptions.
  2. Step 2: Check for syntax or logic errors

    Multiple catch blocks are allowed and correctly ordered from specific to general. The catch blocks have correct parameter types. Throwing an int matches the first catch.
  3. Final Answer:

    No error, code is correct -> Option A
  4. Quick Check:

    Proper catch blocks for thrown int = correct code [OK]
Hint: Multiple catch blocks allowed; order matters [OK]
Common Mistakes:
  • Thinking multiple catch blocks cause error
  • Missing parameter type in catch
  • Throwing incompatible data type
5. Consider this function that throws exceptions based on input: <pre>void checkValue(int x) { if (x < 0) throw std::string("Negative value"); else if (x == 0) throw 0; else throw 3.14; } What is the best way to catch all exceptions thrown by checkValue and print a message for each type accordingly?
hard
A. Use a single catch block with catch(...) only.
B. Use separate catch blocks for std::string, int, and double types.
C. Use only catch(int) block.
D. Use try without any catch block.

Solution

  1. Step 1: Identify exception types thrown

    The function throws three different types: std::string, int, and double.
  2. Step 2: Determine how to catch each type

    To handle each exception properly, separate catch blocks for each type are needed. Using only catch(...) catches all but cannot distinguish types. Catching only int misses others. No catch block causes program termination on exception.
  3. Final Answer:

    Use separate catch blocks for std::string, int, and double types. -> Option B
  4. Quick Check:

    Multiple catch blocks for different types = best practice [OK]
Hint: Catch each thrown type separately for clear handling [OK]
Common Mistakes:
  • Using only catch(...) and missing type info
  • Catching only one exception type
  • Not using any catch block
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard