qfedu-cpp-level/day8/d11.cpp

37 lines
758 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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;
}