c++exceptionconstructorexternthrow

Handling exceptions for extern declared object initialization


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.


Solution

  • 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 catch the exception, you should warp it by a function, such as:

    inline AppState& getAppState() {
        static AppState* appState = nullptr;
        if (appState == nullptr) {
            try {
                appState = new AppState{};
            } catch (std::exception& e) {
                std::cerr << e.what();
            }
        }
        return *appState;
    }
    

    Place this utility function at state.h, and whenever you want to use the appState global, use getAppState() instead.

    Note: using global variable to store states might be a bad idea and may cause some problems including untracked changes and high coupling.