0

I have a try-catch with multiple catch-statements. The catch-statments are about 30 lines of code. Many functions have the same catch-statements. I would like to replace them with a single line of code (which would be defined somewhere, like a macro). Is this possbile with c++ / Microsoft Visual Studio?

try {...}
<INSERT SINGLE LINE OF CODE HERE>

Instead of:

try {...}
catch (HRESULT hr) {...}
catch (std::exception & e) {...}
catch (LPCWSTR e) {...}
catch (...) {...}

Thank you.

  • 2
    Does this answer your question? [How can I abstract out a repeating try catch pattern in C++](https://stackoverflow.com/questions/3561659/how-can-i-abstract-out-a-repeating-try-catch-pattern-in-c) – Zereges Apr 22 '20 at 08:26
  • Thank you for the link. Interesting, but not quite what I was looking for. I simply want to replace. – Silentium Vetzo Apr 23 '20 at 18:00

2 Answers2

2

What is wrong about a function?

void common_handler() { /* handle common */ }

try {...}
catch (HRESULT hr)
{
    common_handler();
    // handle specific
}
catch (std::exception & e)
{
    common_handler();
    // handle specific
}
catch (LPCWSTR e)
{
    common_handler();
    // handle specific
}
catch (...)
{
    common_handler();
    // handle specific
}
Zereges
  • 5,139
  • 1
  • 25
  • 49
0

Read more about C++

Learn to define functions (perhaps static inline ones) or macros, that is use wisely the preprocessor. Take inspiration from several of the many open source C++ projects on github or gitlab or elsewhere.

Regarding the choice of your C++ compiler and your source code editor, consider alternatives. Such as GCC or Clang for the C++ compiler, emacs for the editor, and perhaps ninja or make for your build automation. I also recommend using git as your version control.

I even recommend trying some Linux distribution (such as Ubuntu or Debian), since they are extremely developer friendly and contains a lot of examples of open source C++ code (in particular GCC or Clang or fish or FLTK). See also this.

How do you substitute multiple lines of cpp code?

A possibility is of course to generate some C++ code with another program (your own small C++ metaprogram, a Python script, a Guile one, etc...) then #include that generated C++ file. Look inside RefPerSys for an example (work in progress). Or look inside Qt and its moc or ANTLR : they all generate C++ code.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547