c++ - 在抛出 std::exception 实例后调用终止

标签 c++ exception try-catch

我是异常的新手,我试图改进我的一位 friend 在求职面试中遇到的问题的解决方案。

我的 friend 被要求构建一个程序,它将获得 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!!");
}

你正在抛出一个字符串(实际上是一个const char*),它显然不是继承自你的std::exception稍后再尝试。您可以尝试 throw std::runtime_error("Can not divide by zero!!"); 或抛出 std::invalid_argument,以更适合每种情况的为准. 为什么异常发生似乎已从错误消息中得知。

关于c++ - 在抛出 std::exception 实例后调用终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54828084/

相关文章:

c++ - 如何在端口 80 上运行 Boost.Asio 服务器?

c++ - 如何仅从连接的设备中过滤 Windows api 设备信息?

c++ - 指向二维数组的指针作为函数参数

python - 尝试除了不从类中捕获 IOError 之外

java - 微软sql错误异常

r - R,try或tryCatch,无错误日志

python - 重新引发Python中的错误

c++ - MSBuild 使用错误的(平台)版本的 Tracker.exe

java - TextToSpeech 抛出未知异常

r - 所有连接都在使用中 : Execution halted