Pustovalov Dmitry
Pustovalov Dmitry

Reputation: 1047

Remove exception specifications from C++ code with sed

I want to automatically remove deprecated exception specifications from my c++ code and try to use sed for this task.

Exception specification format is throw following with list of exceptions (words) between parenthesis so I wrote this sed:

sed -r 's,throw\s*[(].*[)],,g' foo.cpp

It works for oneline specifications but does not work for multiline one's.

It seems like dot does not match newlines althougth according to documentation it have to: https://www.gnu.org/software/sed/manual/html_node/Regular-Expressions.html

I tried this workaround but it does not work either (actually it does not even work for oneline specifications):

sed -r 's,throw\s*[(][\s\S]*[)],,g'

How to make it work properly?

EDITED:

example of exception spec:

void foo() throw (std::runtime_error);  //oneline

void bar() throw (std::runtime_error,
                  std::logic_error);    //multiline

Upvotes: 3

Views: 312

Answers (2)

Michael Teske
Michael Teske

Reputation: 11

There is a clang-tidy check for this already.

I got it to replace the throw specifications from our source with noexcept(false) with this commandline

clang-tidy --fix --checks=-*,modernize-use-noexcept foo.cpp -- -I /my/include/path

Compiler options such as include paths and defines need to go after the -- . For further documentation see https://clang.llvm.org/extra/clang-tidy/checks/modernize-use-noexcept.html

Upvotes: 1

Sebastian Redl
Sebastian Redl

Reputation: 71999

Many text editors (for example jEdit) support multi-file regex search & replace.

However, there is no syntactic distinction between a throw specification and a throw expression throwing a parenthesized variable. The two are mostly distinguished primarily by not appearing in the same syntactic context. You could also distinguish them by resolving the name. But that won't work to distinguish the throw expression throw(foo()), which throws a default-constructed object of type foo, and the throw specification throw(foo()), which makes the absurd but technically valid claim that the annotated function may throw an exception of type "function that takes no arguments and returns a foo".

If you want a reliable way of stripping exception specifications, the best way would be to write a Clang Tidy check.

Upvotes: 3

Related Questions