noexcept keyword

Learned in CS247. https://stackoverflow.com/questions/10787766/when-should-i-really-use-noexcept

noexcept is a tag associated with methods (like const), which states the method will never raise an exception, destructors are implicitly noexcept tagged.

noexcept is primarily used to allow “you” to detect at compile-time if a function can throw an exception.

Can noexcept still cause an exception to be thrown?

I think noexcept simply gives you warnings, it won’t prevent you from compiling your code. If an exception is thrown inside a noexcept function, the program will call std::terminate.

For example

#include <iostream>
#include <stdexcept>
 
void throwException() {
    throw std::runtime_error("An exception has occurred");
}
 
void myFunction() noexcept {
    throwException(); // Calls a function that throws an exception
}
 
int main() {
    try {
        myFunction();
    } catch (...) {
        std::cout << "This will never be reached.\n";
    }
 
    return 0;
}
 
// Warning: /Users/stevengong/testenv/nothrow.cpp:5:5: warning: 'myFunction' has a non-throwing exception specification but can still throw [-Wexceptions]
 
// OUTPUT: An Exception has occured

Disabling noexcept for Destructor

By default, destructors are tagged with noexcept, i.e. they cannot throw exceptions.

class A {
	public:
		...
		~A() noexcept (false) {...}
}