Different Exception Types
Part of the Logic & Flow section of Coddy's C++ journey — lesson 51 of 56.
Real-world programs often encounter different types of errors that require different handling approaches. Instead of using a single catch block for all exceptions, you can create multiple catch blocks to handle specific exception types differently.
When you have multiple catch blocks, C++ will check them in order from top to bottom and execute the first one that matches the thrown exception type:
try {
// Code that might throw different types of exceptions
} catch (std::invalid_argument& e) {
std::cout << "Invalid input format!" << std::endl;
} catch (std::out_of_range& e) {
std::cout << "Number is too large!" << std::endl;
} catch (const char* msg) {
std::cout << "Custom error: " << msg << std::endl;
}This approach allows you to provide specific, meaningful responses to different error conditions. For example, when converting user input to numbers, you might catch std::invalid_argument for non-numeric text and std::out_of_range for numbers that are too large to fit in the target data type.
The order of catch blocks matters - place more specific exception types first, followed by more general ones. This ensures that each exception is handled by the most appropriate block, giving users clear feedback about what went wrong and how they might fix it.
Challenge
EasyCreate a program that demonstrates handling multiple types of exceptions using different catch blocks. This challenge will test your understanding of how to provide specific error handling for different exception types that can occur during data processing.
The following inputs will be provided:
- A string
operationrepresenting the type of operation to perform ("convert","divide", or"access") - A string
datathat will be used differently based on the operation type
Your program should:
- Create a function named
processDatathat takes two string parameters - Inside the function, use an if-else structure to handle different operations:
- If operation is
"convert": usestd::stoito convert the data string to an integer and print it - If operation is
"divide": convert the data string to an integer usingstd::stoi, then divide 100 by that number and print the result - If operation is
"access": create a string with value"Hello"and print the character at the index specified by converting data to integer usingstd::stoi - In the main function, call
processDatainside atryblock - Use multiple
catchblocks to handle different exception types in this exact order: - First:
std::invalid_argumentfor invalid string-to-number conversions - Second:
std::out_of_rangefor numbers too large or string index out of bounds - Third:
const char*for custom error messages
Use the following exact output format:
For successful operations:
Result: [result_value]For different exception types:
Invalid argument error
Out of range error
Custom error: [error_message]Remember that C++ checks catch blocks in the order they appear, so place more specific exception types first. The std::stoi function can throw both std::invalid_argument (for non-numeric strings) and std::out_of_range (for numbers too large). String indexing with at() method throws std::out_of_range when the index is beyond the string length. Each catch block should handle its specific exception type and provide appropriate error messages.
Cheat sheet
Use multiple catch blocks to handle different exception types. C++ checks them in order from top to bottom and executes the first matching one:
try {
// Code that might throw different types of exceptions
} catch (std::invalid_argument& e) {
std::cout << "Invalid input format!" << std::endl;
} catch (std::out_of_range& e) {
std::cout << "Number is too large!" << std::endl;
} catch (const char* msg) {
std::cout << "Custom error: " << msg << std::endl;
}Place more specific exception types first, followed by more general ones. This ensures each exception is handled by the most appropriate block.
Common exception types:
std::invalid_argument- for invalid string-to-number conversionsstd::out_of_range- for numbers too large or array/string index out of boundsconst char*- for custom error messages
Try it yourself
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
// TODO: Write your code here
// Create the processData function and implement the try-catch structure
int main() {
// Read input
string operation;
string data;
cin >> operation;
cin >> data;
}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