GeneralPurpose-RethrowWithException

Avoid rethrowing with explicit exception

Required inputs: IR

Use throw; to rethrow an exception. Explicitly rethrowing an exception causes a new temporary exception object to be copy-initialized from the rethrown exception. If the rethrown exception is of a derived type but caught by reference to a base-class type, this copy-initialization will result in object slicing. throw; instead rethrows the current exception without creating a new exception object, thus avoiding this issue.
Bad code (rethrowing current exception):
class Error {};
class LogicError : public Error {};
void foo() {
    try {
        // ...
        throw LogicError();
    } catch(const Error& e) {
        throw e; // ERROR: copy-initializes a new exception object of type Error
    }
}
Good code (rethrowing with throw;):
void foo() {
    try {
        // ...
        throw LogicError();
    } catch(const Error& e) {
        throw; // OK: rethrows the current exception
    }
}

Possible Messages

Key

Text

Severity

Disabled

throw_with_exception

Avoid rethrowing with explicit exception, use just “throw;”.

None

False

Options