Bird
Raised Fist0
C++programming~30 mins

Throwing exceptions in C++ - Mini Project: Build & Apply

Choose your learning style10 modes available
Throwing exceptions
๐Ÿ“– Scenario: Imagine you are writing a simple program that checks if a number is positive. If the number is negative, the program should stop and show an error message.
๐ŸŽฏ Goal: You will create a program that throws an exception when a negative number is found and handles it gracefully.
๐Ÿ“‹ What You'll Learn
Create an integer variable named number with the value -5
Create a boolean variable named checkPositive and set it to true
Use a try block to check if number is negative and throw an exception with the message "Negative number found"
Use a catch block to catch the exception and print the exception message
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Throwing exceptions helps programs stop when something goes wrong, like invalid input or unexpected situations.
๐Ÿ’ผ Career
Understanding exceptions is important for writing safe and reliable C++ programs in software development jobs.
Progress0 / 4 steps
1
Create the number variable
Create an integer variable called number and set it to -5.
C++
Hint

Use int number = -5; to create the variable.

2
Create the checkPositive variable
Create a boolean variable called checkPositive and set it to true.
C++
Hint

Use bool checkPositive = true; to create the variable.

3
Add a try block to throw an exception
Write a try block that checks if number is less than 0. If yes, throw a std::runtime_error exception with the message "Negative number found".
C++
Hint

Use try { if (number < 0) throw std::runtime_error("Negative number found"); }.

4
Add a catch block to handle the exception and print the message
Add a catch block that catches std::runtime_error exceptions by reference as e and prints e.what() using std::cout.
C++
Hint

Use catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; }.

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