Suppose I have code
// state.h
extern struct AppState {
AppState() {
throw std::runtime_error("The runtime error");
}
} appState;
// state.cpp
#include "state.h"
AppState appState = AppState();
How do I catch exception thrown during construction of appState?
Since there's a way to throw exceptions in such situations, I suppose there is a way to catch them.
Unfortunately there's noway to catch an exception thrown by a global variable construction. You may received warnings by code linters when declaring them.
If you really need to
catchthe exception, you should warp it by a function, such as:Place this utility function at
state.h, and whenever you want to use theappStateglobal, usegetAppState()instead.Note: using global variable to store states might be a bad idea and may cause some problems including untracked changes and high coupling.