Learn++ Lesson 44: Noexcept in C++ Programming
The noexcept specifier tells C++ that a function is not expected to throw exceptions. It communicates an important guarantee to readers and the compiler.
Mark a function as noexcept
#include <iostream>
void display() noexcept {
std::cout << "This function won't throw exceptions.";
}
int main() {
display();
return 0;
}
Output:
This function won't throw exceptions.
The display function is marked noexcept and prints a message. The call in main runs normally because the function does not throw.
Why noexcept matters
- It documents that a function should not propagate exceptions.
- It can enable useful optimizations in performance-sensitive code.
- It makes error-handling guarantees visible in a function's interface.
What you practice in the app
- Adding
noexceptto a function declaration. - Calling a non-throwing function from
main. - Reading the output of a simple C++ exception-safety example.
Today's challenge
Fill in the missing function name so the program calls display and prints the shown message:
#include <iostream>
void display() noexcept {
std::cout << "This function won't throw exceptions.";
}
int main() {
_______();
return 0;
}
The unique intended answer is display, the function defined above.