- 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.
- 大數(shù)據(jù)技術(shù)基礎(chǔ)
- 達(dá)夢數(shù)據(jù)庫編程指南
- 輕松學(xué)大數(shù)據(jù)挖掘:算法、場景與數(shù)據(jù)產(chǎn)品
- Voice Application Development for Android
- 正則表達(dá)式必知必會
- 文本數(shù)據(jù)挖掘:基于R語言
- Enterprise Integration with WSO2 ESB
- Learn Unity ML-Agents:Fundamentals of Unity Machine Learning
- 金融商業(yè)算法建模:基于Python和SAS
- 深入淺出 Hyperscan:高性能正則表達(dá)式算法原理與設(shè)計
- 云原生數(shù)據(jù)中臺:架構(gòu)、方法論與實踐
- 辦公應(yīng)用與計算思維案例教程
- Python數(shù)據(jù)分析與挖掘?qū)崙?zhàn)(第3版)
- 淘寶、天貓電商數(shù)據(jù)分析與挖掘?qū)崙?zhàn)(第2版)
- Augmented Reality using Appcelerator Titanium Starter