CodeBlanks Logo Icon CodeBlanks

catch all

Learn to catch all exceptions with catch(...).

Catch all with catch(...)

Sometimes you do not know the exception type in advance; still, you want to prevent the program from crashing. In such cases, you use the catch(...) form. The three dots catch any type of exception.

try {
    riskyCode();
} catch (...) {
    cout << "Unknown error";
}

Here catch(...) runs no matter what type of exception is thrown. But you cannot access the exception's contents; methods like e.what() are not available. catch(...) usually appears as a last resort in the final catch block.

Limitations of catch(...)

catch(...) is handy, but it has limitations. The main one is that you cannot access the exception's contents; methods like e.what() are unavailable. The information about which type was thrown is also lost.

For this reason, it is common practice to use catch(...) as the last block. First, specific catch blocks handle known types; finally, catch(...) collects any exception that did not match. This layout gives specific responses to known errors while still preventing crashes from unknown ones.

Practice Set up a safety net with catch(...)

Inside a try block, write throw 42; (throw an integer). In a catch (...) block, print cout << "Unknown error" << endl;.

Starter code

main.cpp
#include <iostream>
using namespace std;

int main() {
    // in try throw an error, catch it with a safety net
    return 0;
}

Sample solution

main.cpp
#include <iostream>
using namespace std;

int main() {
    try {
        throw 42;
    } catch (...) {
        cout << "Bilinmeyen hata" << endl;
    }
    return 0;
}

Expected output

Unknown error

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: catch all

Question
try {
    riskyCode();
} ____ (...) {
    cout << "Error";
}
Answer
try {
    riskyCode();
} catch (...) {
    cout << "Error";
}

Explanation: catch(...) catches every type.

2 Match each block with its feature

Term Meaning
catch (std::exception&) gives type info
catch (...) catches all types
try surrounds risky code

3 Can e.what() be called inside a catch(...) block?

  • No, there is no exception object Correct answer
  • Yes, always
  • Only after throw
  • Only with const

Explanation: catch(...) has no exception object name; e.what() cannot be called.

All lessons in Beginner