c++ - 抛出 std::exception 的实例后调用终止
问题描述
我是例外的新手,我试图改进我的一个朋友在面试中遇到的问题的解决方案。
我的朋友被要求构建一个程序,它将获取 2 个数组并找到一个数字,如果我们将它除以第一个数组的成员,我们将得到第二个数组的匹配剩余部分。
在这种情况下,我可以在没有任何继承类的情况下使用 std::exception 吗?
CPP文件
#include <iostream>
#include <exception>
#include "FindNumber.h"
Finder::Finder() : m_num(0)
{}
int Finder::FindFirst(int* _divided, int* _leftOver, int _size)
{
int indx = 0;
while(indx < _size)
{
if (!_divided[indx])
{
throw("Can not divide by zero!!");
}
if (m_num % _divided[indx] != _leftOver[indx])
{
++m_num;
FindRest(_divided, _leftOver, _size);
indx = 0;
}
++indx;
}
return m_num;
}
int Finder::FindRest(int* _divided, int* _leftOver, int _size)
{
int indx = 0;
for(;;)
{
if (!_divided[indx])
{
throw("Can not divide by zero!!");
}
if (m_num % _divided[indx] != _leftOver[indx])
{
++m_num;
}
else
{
break;
}
}
return m_num;
}
测试单元
#include <cstdio>
#include <iostream>
#include "FindNumber.h"
#include "mu_test.h"
#define SIZE 5
/****************************** FN_check1 ******************************/
UNIT(FN_check1)
int divided [SIZE] = {0, 4, 5, 6, 7};
int leftOver [SIZE] = {2, 0, 3, 2, 1};
Finder find1;
try
{
ASSERT_THAT(6 != find1.FindFirst(divided, leftOver, SIZE));
ASSERT_THAT(8 == find1.FindFirst(divided, leftOver, SIZE));
}
catch(std::exception& e)
{
std::cout << e.what();
}
END_UNIT
/****************************** FN_check2 ******************************/
UNIT(FN_check2)
int divided [SIZE] = {6, 12, 8, 10, 7};
int leftOver [SIZE] = {0, 0, 4, 2, 5};
Finder find1;
ASSERT_THAT(6 != find1.FindFirst(divided, leftOver, SIZE));
ASSERT_THAT(12 == find1.FindFirst(divided, leftOver, SIZE));
std::cout << find1.FindFirst(divided, leftOver, SIZE) << std::endl;
END_UNIT
TEST_SUITE(FindNumber_test)
TEST(FN_check1)
TEST(FN_check2)
END_SUITE
提前致谢...
解决方案
如下所示的用于引发异常的行:
if (!_divided[indx]) {
throw("Can not divide by zero!!");
}
您正在throw
输入一个字符串(实际上是 a const char*
),它显然不会继承std::exception
您稍后尝试捕获的内容。您可以尝试throw std::runtime_error("Can not divide by zero!!");
或抛出一个std::invalid_argument
,以更适合每种情况为准。错误消息似乎知道为什么会发生异常。
推荐阅读
- node.js - 第二个用户不创建
- java - 让 Maven/jetty 应用程序在 GCE 上永久运行
- powerbi - 功率双速计显示最后一个值
- php - 在php中组合子字符串
- ios - Ionic 应用程序 - IOS 低功耗模式阻止视频加载
- java - 泛型类型上的 Stream 操作链导致类型错误
- r - 将学习者与 mlr 中的预处理融合在一起——使用什么设置?
- c++ - 基于作为参数接收的函数定义具有模板化 Key 类型的 std::map
- ruby-on-rails - 如何使用 Rails 通过 OAuth 访问 WP REST API
- angular - 如何观察“searchTerm”输入字段的值变化?