Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
β Incorrect
Throwing an integer value like 1 is a simple way to signal an exception in C++.
2fill in blank
mediumComplete 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'
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.
β Incorrect
The catch block must match the thrown exception type, which is std::string here.
3fill in blank
hardFix 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'
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.
β Incorrect
Using catch(...) catches any type of exception regardless of its type.
4fill in blank
hardFill 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'
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.
β Incorrect
Throw an instance of MyException and catch it by reference to MyException.
5fill in blank
hardFill 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Throwing a float but catching int causes mismatch.
Printing a variable not declared in catch causes errors.
β Incorrect
Throw integer 42, catch as int, and print the caught variable e.