// exception 的使用 // invalid_argument: 用于处理无效参数异常 #include #include #include #include using namespace std; int maxVal(int a, int b) { if (a == b) { char msg[100]; sprintf(msg, "两个参数不能相等,a = %d, b = %d", a, b); throw invalid_argument(msg); } return a > b ? a : b; } int main(int argc, char const *argv[]) { int a = atoi(argv[1]); int b = atoi(argv[2]); try { int ret = maxVal(a, b); cout << "maxValue is " << ret << endl; } catch (exception &error) { cout << "error: " << error.what() << endl; // what() 返回异常信息,异常信息是一个字符串 } return 0; }