...
In this noncompliant code example, the second function claims to throw only exception1
Exception1
, but it may also throw exception2
Exception2
:
Code Block |
---|
|
#include <exception>
class exception1Exception1 : public std::exception {};
class exception2Exception2 : public std::exception {};
void foo() {
throw exception2Exception2{}; // Okay because foo() promises nothing about exceptions
}
void bar() throw (exception1Exception1) {
foo(); // Bad because foo() can throw exception2Exception2
}
|
Compliant Solution
This compliant solution catches the exceptions thrown by foo()
:
Code Block |
---|
|
#include <exception>
class Exception1 : public std::exception {};
class Exception2 : public std::exception {};
void foo() {
throw Exception2{}; // Okay because foo() promises nothing about exceptions
}
void bar() throw (exception1Exception1) {
try {
foo();
} catch (exception2Exception2 e) {
// Handle error without rethrowing it
}
}
|
...
This compliant solution declares an a dynamic exception-specification for bar()
, which covers all of the exceptions that can be thrown from it:
Code Block |
---|
|
#include <exception>
class Exception1 : public std::exception {};
class Exception2 : public std::exception {};
void foo() {
throw Exception2{}; // Okay because foo() promises nothing about exceptions
}
void bar() throw (exception1Exception1, exception2Exception2) {
foo();
} |
Noncompliant Code Example
...
Code Block |
---|
|
#include <cstddef>
#include <vector>
void f(std::vector<int> &v, size_t s) noexcept(true) {
v.resize(s); // May throw
}
|
...
Code Block |
---|
|
#include <cstddef>
#include <vector>
void f(std::vector<int> &v, size_t s) {
v.resize(s); // May throw, but that is okay
} |
...