0
0
C++programming~10 mins

Why exception handling is required in C++ - Test Your Understanding

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 by the division by zero.

C++
#include <iostream>
int main() {
    try {
        int a = 10, b = 0;
        if (b == 0) throw [1];
        std::cout << a / b << std::endl;
    } catch (int e) {
        std::cout << "Exception caught: division by zero" << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A1
B0
Cb
Da
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Throwing a variable that is zero poorly signals an error.
Throwing the variable 'b' which is zero is not meaningful here.
2fill in blank
medium

Complete the code to handle an exception of type std::string.

C++
#include <iostream>
#include <string>
int main() {
    try {
        throw std::string("Error occurred");
    } catch ([1] e) {
        std::cout << "Caught exception: " << e << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Aint
Bstd::string
Cfloat
Dchar
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Catching with int or char causes a mismatch and no catch.
Catching with float is incorrect for string exceptions.
3fill in blank
hard

Fix the error in the code by completing the catch block to handle all exceptions.

C++
#include <iostream>
int main() {
    try {
        throw 20;
    } catch ([1]) {
        std::cout << "Exception caught" << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Afloat e
Bchar e
Cint e
D...
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using catch(int e) only catches int exceptions.
Using catch(char e) or catch(float e) misses other types.
4fill in blank
hard

Fill both blanks to throw and catch a custom exception class.

C++
#include <iostream>
class MyException {
public:
    const char* what() const { return "Custom exception"; }
};
int main() {
    try {
        throw [1];
    } catch ([2]& e) {
        std::cout << e.what() << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
AMyException()
Bint
CMyException
Dstd::exception
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Throwing the class name instead of an instance causes errors.
Catching by value instead of reference can cause slicing.
5fill in blank
hard

Fill all three blanks to create a try-catch block that throws an integer, catches it, and prints the value.

C++
#include <iostream>
int main() {
    try {
        throw [1];
    } catch ([2] e) {
        std::cout << "Caught value: " << [3] << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A42
Bint
Ce
Dfloat
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Throwing a float but catching int causes mismatch.
Printing a variable not declared in catch causes errors.