Exception handling handles runtime errors, including throwing, catching and handling exceptions. Exception specifiers are used to specify the types of exceptions that a function can throw, including noexcept(expr) (specifying that no exceptions are thrown) and throw() (specifying that any type of exception can be thrown). In the actual case, the print_file function uses the throw() specifier, and uses the try-catch block to catch the std::runtime_error exception in the main function and handle the file opening error.
Exception handling and exception specifiers of C functions
Exception handling is the key mechanism for handling runtime errors. It is divided into Three parts: throwing exceptions, catching exceptions and handling exceptions. In C, exceptions are represented by exception classes.
Throw an exception
Use the throw
keyword to throw an exception. An exception class or any object with specific functionality can serve as an exception. For example:
throw std::runtime_error("失败!");
Catch exceptions
Use try-catch
block to catch exceptions. try
blocks contain code that may throw exceptions, while catch
blocks specify how to handle different types of exceptions. For example:
try { // 可能抛出异常的代码 } catch (const std::runtime_error& e) { // 处理 std::runtime_error 异常 } catch (const std::exception& e) { // 处理所有其他异常 }
Exception specifier
The exception specifier is added to the function signature to specify the types of exceptions that the function can throw. There are two exception specifiers:
expr
is a constant expression. Practical Case
Consider a function that reads a file and prints it to the console. This function may throw an exception because the file does not exist or access is denied. We can use exception specifiers and try-catch
blocks to handle these situations.
#include <iostream> #include <fstream> void print_file(const std::string& file_name) { std::ifstream file(file_name); if (!file.is_open()) throw std::runtime_error("无法打开文件!"); std::string line; while (std::getline(file, line)) { std::cout << line << std::endl; } } int main() { try { print_file("test.txt"); } catch (const std::runtime_error& e) { std::cerr << e.what() << std::endl; } return 0; }
In function print_file
, the exception specifier throw()
specifies that the function can throw any type of exception. In the main
function, we use a try-catch
block to handle exceptions. If an error occurs while opening the file, a std::runtime_error
exception is thrown and an error message is printed to the console.
The above is the detailed content of Exception handling and exception specifiers for C++ functions. For more information, please follow other related articles on the PHP Chinese website!