- Hands-On System Programming with C++
- Dr. Rian Quinn
- 298字
- 2021-07-02 14:42:30
Error handling mechanism in C++
Error handling is another issue with C. The problem, at least until set jump exceptions were added, was that the only ways to get an error code from a function were as follows:
- Constrain the output of a function, so that certain output values from the function could be considered an error
- Get the function to return a structure, and then manually parse that structure
For example, consider the following code:
struct myoutput
{
int val;
int error_code;
}
struct myoutput myfunc(int val)
{
struct myoutput = {0};
if (val == 42) {
myoutput.error_code = -1;
}
myoutput.val = val;
return myoutput;
}
void
foo(void)
{
struct myoutput = myfunc(42);
if (myoutput.error_code == -1) {
printf("yikes\n");
return;
}
}
The preceding example provides a simple mechanism for outputting an error from a function without having to constrain the output of the function (for example, by assuming that -1 is always an error).
In C++, this can be implemented using the following C++17 logic:
std::pair<int, int>
myfunc(int val)
{
if (val == 42) {
return {0, -1};
}
return {val, 0};
}
void
foo(void)
{
if (auto [val, error_code] = myfunc(42); error_code == -1) {
printf("yikes\n");
return;
}
}
In the preceding example, we were able to remove the need for a dedicated structure by leveraging std::pair{}, and we were able to remove the need to work with std::pair{} by leveraging an initializer_list{} and C++17-structured bindings.
There is, however, an even easier method for handling errors without the need for checking the output of every function you execute, and that is to use exceptions. C provides exceptions through the set jump API, while C++ provides C++ exception support. Both of these will be discussed at length in Chapter 13, Error - Handling with Exceptions.
- Python數據分析與挖掘實戰
- SQL查詢:從入門到實踐(第4版)
- UDK iOS Game Development Beginner's Guide
- 城市計算
- 大話Oracle Grid:云時代的RAC
- Power BI商業數據分析完全自學教程
- Hands-On Mathematics for Deep Learning
- 網站數據庫技術
- Proxmox VE超融合集群實踐真傳
- gnuplot Cookbook
- 重復數據刪除技術:面向大數據管理的縮減技術
- 辦公應用與計算思維案例教程
- Hadoop大數據開發案例教程與項目實戰(在線實驗+在線自測)
- Web Services Testing with soapUI
- 中國云存儲發展報告