[英]Terminate called after throwing an instance of std::exception
I'm new to exceptions and I tried to improve a solution for question that one of my friend had in a job interview. 我是特例的新手,我试图改善一个朋友面试中遇到的问题的解决方案。
My friend was asked to build a program which will get 2 arrays and find a number, which if we divide it by the members of the first array, we will get a matching leftover of the second array. 我的朋友被要求构建一个程序,该程序将获得2个数组并找到一个数字,如果将其除以第一个数组的成员,我们将得到一个匹配的第二个数组的剩余物。
Can I use std::exception without any inheriting classes in this case? 在这种情况下,我可以在没有任何继承类的情况下使用std :: exception吗?
THE CPP FILE 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;
}
THE TEST UNIT 测试单元
#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
Thanks in advance... 提前致谢...
Lines like below that you use to throw exceptions: 下面的行用于引发异常:
if (!_divided[indx]) {
throw("Can not divide by zero!!");
}
You are throw
ing a string (actually a const char*
), which obviously does not inherit from std::exception
which you try to catch later on. 您将
throw
一个字符串(实际上是const char*
),该字符串显然不会继承自std::exception
,您稍后会尝试捕获它。 You could try to throw std::runtime_error("Can not divide by zero!!");
您可以尝试
throw std::runtime_error("Can not divide by zero!!");
or throw a std::invalid_argument
, whichever is more appropriate for each situation. 或抛出
std::invalid_argument
,这对于每种情况都更合适。 Why the exception occurs seems to be known by the error message. 错误消息似乎知道为什么发生异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.