为什么catch中的代码没有被执行

Why code inside catch does not get executed

本文关键字:执行 代码 catch 为什么      更新时间:2023-10-16

我有一个Foo类,如下

Foo.h

#pragma once
class Foo
{
public:
Foo() = default;
~Foo() = default;
void DoSomething();
};

Foo.cpp

#include "Foo.h"
void Foo::DoSomething()
{
throw "something happened";
}

我使用的类是:

#include <iostream>
#include "Foo.h"
int main()
{
try
{
Foo foo;
foo.DoSomething();
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}

我希望代码进入catch块。然而,它从来没有进入那里。我在这里做错了什么?

进行时

throw "something happened"

你不是在扔std::exception。您正在抛出一个类型为const char[N]的字符串文字。要捕捉它,你需要一个像这样的捕捉块

catch (const char* e)
{
std::cout << e << std::endl;
}

或者,你可以抛出一些从std::exception派生的东西,比如std::runtime_error,看起来像

void Foo::DoSomething()
{
throw std::runtime_error("something happened");
}
...
catch (const std::exception& e) // catch by reference to const
{
std::cout << e.what() << std::endl;
}

您还可以指定一个默认的处理程序,如

catch (...)
{
std::cout << "something bad happened - cannot recover" << std::endl;
}

它将捕获任何抛出的异常,但您将无法访问抛出的任何异常,因此只能给出一般消息。