我一生中没有碰太多例外,我尝试改善一个朋友面试中遇到的问题的解决方案。
在这个问题中,我被要求构建一个程序,该程序将获得2个数组并找到一个数字,如果将其除以第一个数组中的成员,则将在第二个数组中获得匹配的剩余物。
在这种情况下,我可以在没有任何继承类的情况下使用std :: exception吗? 为什么为什么我会在抛出“ char const *”实例后收到终止调用?
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
预先感谢...
答案 0 :(得分:1)
以下用于引发异常的行:
<xtmhtml:attribute-text>bjabber</xtmhtml:attribute-text>
<xtmhtml:inline text="'>"/>
<xtmhtml:segment>IMPORTANT NOTICES AND DISCLAIMERS - PLEASE READ</xtmhtml:segment>
您正在//xtmhtml:segment/preceding-sibling[2]/text()
//xtmhtml:segment/preceding-sibling::xtm:inline/preceding-sibling::xtmhtml:attribute-text/text()
输入一个字符串(实际上是if (!_divided[indx]) {
throw("Can not divide by zero!!");
}
),该字符串显然不会继承自您稍后尝试捕获的throw
。您可以尝试const char*
或抛出std::exception
,以每种情况为准。 为什么错误消息似乎已知道发生了异常。