Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace dynamic exception specifications: throw(...)

I am working on a project that uses a legacy library which uses function definitions like

void func() throw(some_exception);

Since dynamic exception specifications are removed in C++17 I am wondering how to address this problem.

  1. P0003R0 suggests to replace

    void func() throw(some_exception)
    {
        /* body */ 
    }
    

    with something like

    void func()
    {
        try
        {
            /* body */
        }
        catch(const some_exception&) {
           throw;
        }
    }
    

    However, I do not have access to the source code (only the header files).

  2. So I am left with trying to "fix" the function definition in the header. So e.g. I could write

    void func() noexcept(false);
    

    But when the function throws an exception, my application still terminates.

How can I change the function definition in the header files or possibly adjust my own project (the places where i use func) to obtain the same behaviour as throw(some_exception) had before C++17?

like image 946
Phil-ZXX Avatar asked Jan 17 '19 15:01

Phil-ZXX


People also ask

What is the dynamic exception specifications syntax?

The dynamic exception specifications syntax uses the throw keyword to list which exception types a function might directly or indirectly throw:

How to disable dynamic exception in C++?

Just remove the dynamic exception specification. That's all you need to do. C++ is not Java; in C++, all functions are (at a language level) assumed to throw anything unless they are tagged noexcept. As such, if you remove the exception specification, it will work exactly as it did before.

What types are not allowed in a non-throwing dynamic exception?

A function with a non-throwing dynamic exception specification does not allow any exceptions. Incomplete types, pointers or references to incomplete types other than cv void*, and rvalue reference types are not allowed in the exception specification.

How do you know if a function is throwing an exception?

If a function is declared with type T listed in its dynamic exception specification, the function may throw exceptions of that type or a type derived from it. A dynamic exception speficification without a type-id list (i.e. throw()) is non-throwing.


1 Answers

Just remove the dynamic exception specification. That's all you need to do.

C++ is not Java; in C++, all functions are (at a language level) assumed to throw anything unless they are tagged noexcept. As such, if you remove the exception specification, it will work exactly as it did before.

like image 140
Nicol Bolas Avatar answered Nov 03 '22 03:11

Nicol Bolas