qfedu-cpp-level/day8/homework/h5.cpp

40 lines
1.2 KiB
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.

// 编写一个C++ 函数 divideNumbers接受两个整数作为参数并返回它们的商。 在函数中处理以下异常情况: 1如果除数为0则抛出 std::logic_error 异常类的一个实例,并传递适当的错误消息。 2如果被除数为0则抛出 std::runtime_error 异常类的一个实例,并传递适当的错误消息。
// 【要求】在 main 函数中调用 divideNumbers并捕获并处理可能抛出的异常。
#include <bits/stdc++.h>
using namespace std;
int divideNumbers(int a, int b)
{
if (b == 0)
throw std::logic_error("除数为0");
if (a == 0)
throw std::runtime_error("被除数为0");
return a / b; // 结果为整数商
}
int main()
{
try
{
cout << "请输入两个整数:" << endl;
int a, b;
cin >> a >> b;
cout << a << "" << b << " 的商为:" << divideNumbers(a, b) << endl;
}
catch (const std::logic_error &e)
{
cout << "捕获异常:" << e.what() << endl;
}
catch (const std::runtime_error &e)
{
cout << "捕获异常:" << e.what() << endl;
}
catch (...)
{
cout << "捕获其他异常" << endl;
}
return 0;
}