qfedu-cpp-level/day8/d11.cpp

37 lines
758 B
C++
Raw Normal View History

2023-08-02 19:23:29 +08:00
// exception 的使用
// invalid_argument: 用于处理无效参数异常
#include <iostream>
#include <cstdlib>
#include <exception>
#include <cstdio>
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;
}