C++ Catch All (...)

beginner
11 min

C++ Catch All (...)

Welcome to our comprehensive guide on the C++ Catch All (...). This tutorial is designed to help both beginners and intermediates understand this powerful feature in the C++ programming language. Let's dive in!

What is Catch All (...)? šŸŽÆ

The ... operator in C++ is known as the variadic template or function with variable number of arguments. It allows a function to take a variable number of arguments of any type. In the context of catch blocks, it's used as a catch-all to handle exceptions of any type.

Why use Catch All (...)? šŸ’”

Imagine you have a function that performs a certain operation on any type of data. If an exception occurs at any point during the execution, you'd want to catch and handle it appropriately. With the ... operator, you can create a catch-all block to handle any exceptions that might occur.

Basic Example šŸ“

cpp
#include <iostream> #include <exception> #include <stdexcept> void handle_exception(std::exception const & e) { std::cerr << "Error occurred: " << e.what() << std::endl; } int main() { try { // Example of throwing an exception throw std::runtime_error("Something went wrong!"); } catch (...) { // Catch all exceptions here handle_exception(std::current_exception()); } return 0; }

In this example, we define a simple function called handle_exception that outputs an error message. In the main function, we throw an exception and catch it using the ... operator. When an exception is caught, it is passed to the handle_exception function for processing.

Advanced Example šŸ“

Let's create a more practical example where we define a logging function that logs messages of different types.

cpp
#include <iostream> #include <string> #include <sstream> #include <exception> #include <stdexcept> #include <vector> #include <typeinfo> template <typename T> void log_message(const T & message) { std::stringstream ss; ss << typeid(T).name() << ": " << message.what(); std::cout << ss.str() << std::endl; } void handle_exception(std::exception const & e) { log_message(e); } int main() { try { // Example of throwing an exception throw std::runtime_error("Something went wrong!"); } catch (...) { // Catch all exceptions here and log them handle_exception(std::current_exception()); } return 0; }

In this example, we define a log_message function that logs the type and message of an exception. When an exception is caught, it is passed to the handle_exception function, which calls log_message to output the exception details.

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

What is the `...` operator in C++ known as?

Quick Quiz
Question 1 of 1

What is the purpose of the `handle_exception` function in the advanced example?