0
0
C++programming~10 mins

Try–catch block 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 catch an exception thrown inside the try block.

C++
try {
    throw std::runtime_error("Error occurred");
} catch ([1]) {
    std::cout << "Exception caught" << std::endl;
}
Drag options to blanks, or click blank then click option'
Aconst std::exception& e
Bint e
Cdouble e
Dchar e
Attempts:
3 left
💡 Hint
Common Mistakes
Catching exceptions by value instead of by reference.
Using incorrect exception types like int or char.
2fill in blank
medium

Complete the code to throw a standard exception with a message.

C++
void test() {
    [1] std::runtime_error("Something went wrong");
}
Drag options to blanks, or click blank then click option'
Athrow
Bcatch
Ctry
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using try or catch instead of throw.
Forgetting to throw the exception object.
3fill in blank
hard

Fix the error in the catch block to properly catch all exceptions.

C++
try {
    // some code
} catch ([1]) {
    std::cout << "Caught an exception" << std::endl;
}
Drag options to blanks, or click blank then click option'
Aint e
Bstd::exception e
Cchar e
D...
Attempts:
3 left
💡 Hint
Common Mistakes
Catching exceptions by value instead of reference.
Not catching all exception types.
4fill in blank
hard

Fill both blanks to catch a standard exception and print its message.

C++
try {
    throw std::runtime_error("Error");
} catch ([1]) {
    std::cout << e.[2]() << std::endl;
}
Drag options to blanks, or click blank then click option'
Aconst std::exception& e
Bwhat
Cmessage
Dconst char* e
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect exception types.
Trying to access a non-existent method like message().
5fill in blank
hard

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

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

int main() {
    try {
        [2] MyException();
    } catch ([3]) {
        std::cout << e.what() << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Awhat
Bthrow
Cconst MyException& e
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Not overriding what() correctly.
Catching exceptions by value instead of reference.
Using catch keyword incorrectly.