The Catch-All Handler
Part of the Logic & Flow section of Coddy's C++ journey — lesson 52 of 56.
Sometimes your program might encounter unexpected errors that don't fit into the specific exception types you've planned for. The catch-all handler catch(...) provides a safety net that catches any exception that wasn't handled by your more specific catch blocks.
The catch-all handler uses three dots (...) instead of specifying a particular exception type. It must be placed after all other catch blocks since C++ checks them in order:
try {
// Code that might throw various exceptions
} catch (std::invalid_argument& e) {
std::cout << "Invalid input!" << std::endl;
} catch (std::out_of_range& e) {
std::cout << "Number too large!" << std::endl;
} catch (...) {
std::cout << "An unexpected error occurred!" << std::endl;
}The catch-all handler acts as a fallback for any exception type that wasn't caught by the previous blocks. This is particularly useful when working with code that might throw exceptions you haven't anticipated, ensuring your program doesn't crash from unexpected errors.
While you can't access the specific details of the exception in a catch-all block, you can still provide a generic error message and perform cleanup operations to keep your program running smoothly.
Challenge
EasyCreate a program that demonstrates comprehensive exception handling using multiple catch blocks including a catch-all handler. This challenge will test your understanding of how to handle both specific exception types and unexpected errors that don't fit into predefined categories.
The following inputs will be provided:
- A string
testTyperepresenting the type of test to perform ("string_convert","math_operation","array_access", or"unknown_error") - A string
value1that will be used as the primary data for the operation - A string
value2that will be used as secondary data for some operations
Your program should:
- Create a function named
performTestthat takes three string parameters - Inside the function, use an if-else structure to handle different test types:
- If testType is
"string_convert": usestd::stoito convert value1 to an integer and print it - If testType is
"math_operation": convert both value1 and value2 to integers usingstd::stoi, then divide value1 by value2 and print the result - If testType is
"array_access": create a string"Programming", convert value1 to an integer index usingstd::stoi, then usestr.at(index)to access the character at that index and print it. The.at()method automatically throwsstd::out_of_rangeif the index is invalid — no manual bounds checking is needed - If testType is
"unknown_error": throw an integer value999 - In the main function, call
performTestinside atryblock - Use multiple
catchblocks to handle exceptions in this exact order: - First:
std::invalid_argument&for invalid string-to-number conversions - Second:
std::out_of_range&for numbers too large or string index out of bounds - Third:
catch(...)as the catch-all handler for any other exception types
Use the following exact output format:
For successful operations:
Success: [result_value]For different exception types:
Invalid argument caught
Out of range caught
Unknown exception caughtRemember that the catch-all handler catch(...) must be placed last since C++ checks catch blocks in order. This handler will catch any exception type that wasn't handled by the previous specific catch blocks, including the integer exception thrown in the "unknown_error" case. The catch-all handler provides a safety net for unexpected errors while still allowing specific handling for known exception types.
Cheat sheet
The catch-all handler catch(...) provides a safety net that catches any exception not handled by specific catch blocks.
The catch-all handler uses three dots (...) and must be placed after all other catch blocks since C++ checks them in order:
try {
// Code that might throw various exceptions
} catch (std::invalid_argument& e) {
std::cout << "Invalid input!" << std::endl;
} catch (std::out_of_range& e) {
std::cout << "Number too large!" << std::endl;
} catch (...) {
std::cout << "An unexpected error occurred!" << std::endl;
}The catch-all handler acts as a fallback for any exception type that wasn't caught by previous blocks. While you can't access specific exception details in a catch-all block, you can provide generic error messages and perform cleanup operations.
Try it yourself
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
// TODO: Write your code here - create the performTest function
int main() {
// Read input
string testType;
string value1;
string value2;
cin >> testType;
cin >> value1;
cin >> value2;
// TODO: Write your code below - implement try-catch blocks and call performTest
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items8Basic Error Handling
Introduction to ExceptionsThe 'try' and 'catch' BlocksThe 'throw' KeywordDifferent Exception TypesThe Catch-All HandlerRecap - Safe Division