C Function parameter error handling can use the following techniques in practice: Exceptions: Use try-catch blocks to catch exceptions and provide error information. Assertions: Use assertions to check parameter validity and terminate the program on failure and print an error message. Error code: The function returns an error code to indicate an error condition.
C Function parameter error handling practice
In software development, function parameter error handling is crucial, it can prevent Invalid or inconsistent input can cause a program to crash or behave unexpectedly. C provides a variety of techniques for efficiently handling function parameter errors.
1. Using Exceptions
C provides the exception
class to handle error situations. We can use the try-catch
block to catch exceptions in the function:
void function(int n) { try { if (n < 0) throw std::invalid_argument("n must be non-negative."); // 函数逻辑... } catch (const std::invalid_argument& e) { std::cerr << "Error: " << e.what() << std::endl; } }
2. Use assertions
Assertions can check the validity of function parameters . If the assertion fails, it will terminate the program and print an error message.
void function(int n) { assert(n >= 0); // 函数逻辑... }
3. Return error code
The function can return an error code to indicate an error situation. For example:
int divide(int a, int b) { if (b == 0) return -1; // 错误码:除数为零 return a / b; }
Practical case
The following is an example of using exceptions to verify function parameters:
// 计算圆的面积 double area_circle(double radius) { if (radius < 0) throw std::invalid_argument("Radius must be non-negative."); return M_PI * radius * radius; } int main() { try { double result = area_circle(-2.5); // 触发异常 } catch (const std::invalid_argument& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }
Output:
Error: Radius must be non-negative.
The above is the detailed content of C++ function parameter error handling practice. For more information, please follow other related articles on the PHP Chinese website!