0
0
C++programming~10 mins

Throwing exceptions in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to throw an exception with the message "Error occurred".

C++
throw [1];
Drag options to blanks, or click blank then click option'
A"Error occurred"
Bthrow
Cstd::exception
DError occurred
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Forgetting the quotes around the error message.
Trying to throw the keyword 'throw' itself.
Throwing an undefined variable.
2fill in blank
medium

Complete the code to throw a standard exception object.

C++
throw [1]();
Drag options to blanks, or click blank then click option'
Astd::exception
Bexception
Clogic_error
Druntime_error
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Omitting the std:: namespace prefix.
Using a class that does not exist or is misspelled.
Throwing the class name without parentheses.
3fill in blank
hard

Fix the error in the code to correctly throw an integer exception.

C++
throw [1];
Drag options to blanks, or click blank then click option'
A"5"
Bint
C5
Dthrow
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using quotes around the number, making it a string.
Throwing the keyword 'throw' instead of a value.
Throwing the type name 'int' instead of a value.
4fill in blank
hard

Fill both blanks to throw a logic_error exception with a message.

C++
throw [1]("[2] error");
Drag options to blanks, or click blank then click option'
Astd::logic_error
Bruntime_error
Clogic_error
Derror
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the class name without the std:: prefix.
Passing a variable name instead of a string message.
Using the wrong exception class.
5fill in blank
hard

Fill all three blanks to throw a custom exception with a message.

C++
class MyException : public std::exception {
public:
    const char* what() const noexcept override {
        return "[1]";
    }
};

throw [2](); // Throw the custom exception

// Catch block example
try {
    // code that throws
} catch (const [3]& e) {
    std::cout << e.what();
}
Drag options to blanks, or click blank then click option'
ACustom error occurred
BMyException
Dstd::exception
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Not overriding the what() method correctly.
Throwing or catching the wrong exception type.
Returning a non-string from what().