Search code examples
c++regexbashsedexception-specification

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

Solution

  • 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.