Home >Backend Development >C++ >What is the difference between C++ function error handling and exception handling?
In C, error handling and exception handling are different mechanisms for handling unexpected situations. Error handling uses the errno global variable or the GetLastError() function to set the error code, and the developer needs to manually check the error. Exception handling throws or captures exception objects, including error information and types, and the compiler automatically handles error propagation and recovery. The main differences include:
The difference between C function error handling and exception handling
In C, error handling and exception handling are Different mechanisms for handling unexpected situations.
Error handling
errno
global variable (POSIX standard) or the GetLastError()
function (Windows API) to set an error code. // 打开文件 FILE* fp = fopen("file.txt", "r"); // 检查错误 if (fp == NULL) { int errnum = errno; // 根据 errnum 采取适当的措施 }
Exception handling
class MyException : public exception { public: const char* what() const noexcept { return "This is an example exception."; } }; // 抛出一个异常 throw MyException(); // 捕获异常 try { // 代码可能抛出异常 } catch (MyException& e) { // 处理 MyException 异常 }
Key differences
Features | Error handling | Exception handling |
---|---|---|
Complexity | Low | High |
Control | Manual error checking by developers | Automatic by compiler |
Code only | Error types and information | |
None | Can create custom exception types | |
Fast | Slower |
Consider Functions that use file operations. We can throw the
FileNotFoundException exception when the file fails to open and handle the exception in the main program. <pre class='brush:cpp;toolbar:false;'>// 定义文件未找到异常
class FileNotFoundException : public exception {
public:
const char* what() const noexcept {
return "File not found.";
}
};
// 打开文件的函数
void openFile(const char* filename) {
FILE* fp = fopen(filename, "r");
if (fp == NULL) {
throw FileNotFoundException();
}
}
// 主程序
int main() {
try {
openFile("myfile.txt");
} catch (FileNotFoundException&) {
cout << "File not found." << endl;
}
}</pre>
The above is the detailed content of What is the difference between C++ function error handling and exception handling?. For more information, please follow other related articles on the PHP Chinese website!