有没有更好的方法来处理异常? try-catch块真的很丑

Is there a better way to handle exceptions ? try-catch block is really ugly

本文关键字:try-catch 真的 异常 更好 方法 处理 有没有      更新时间:2023-10-16

我读了这篇文章,发现处理异常很重要,我使用nlohmann::json(来自 github(,几乎在我的大多数成员函数中都使用nlohmann::json::parsenlohmann::json::dump如果输入有问题,它们有机会抛出异常。

所以我需要处理那些抛出异常的机会

,如下所示:
bool my_class::function(const std::string& input) const
try
{
using namespace nlohmann;
const auto result = json::parse(input);
const auto name = result["name"].dump();
/* and ... */
}
catch (const std::exception& e)
{
/* handle exception */
}

但是我想知道哪一行代码会引发异常,所以如果我写这样的东西:

bool my_class::function(const std::string& input) const
{
using namespace nlohmann;
try
{
const auto result = json::parse(input);
}
catch(const std::exception& e)
{
/* handle exception */
}
try
{
const auto name = result["name"].dump();
}
catch(const std::exception& e)
{
/* handle exception */
}
/* and ... */
}

它给我留下了数千个尝试捕获块。处理异常是更好的原因?

我会这样说: 设置一个"序列指针"来记录你尝试解析的位置/内容,就像使用一个字符串,其中的模式试图解析一个...,这样你就可以知道/通知JSON中错误的元素到底在哪里。

在下面的示例中,如果"name 有问题,则 r 持有值"尝试解析名称",因此在异常中,您可以获得有关导致问题的 JSON 元素的信息:)

bool my_class::function(const std::string& input) const
{
std::string r{""};
try
{
using namespace nlohmann;
r="trying to parse input";
const auto result = json::parse(input);
r="trying to parse name";
const auto name = result["name"].dump();
r="trying to parse age";
const auto age = result["age"].dump();
/* and ... */
}
catch (const std::exception& e)
{
/* handle exception */
}
}

您可能已经注意到,C++没有可用的此信息。 @ΦXocę웃Пepeúpaツ提供了一些很好的解决方法。

让我提供一些其他观点,作为您程序的最终用户,我对程序失败的代码行不感兴趣。我提供的 JSON 要么正确,要么不正确。在第二种情况下,我想知道我需要做什么才能修复 JSON。查看定义异常的代码,这看起来非常详细。

你对它感兴趣的时刻是你在程序中编写了一个错误并且你得到意外错误的时候。此时,最好将调试器附加到程序并单步执行,同时中断引发任何异常。这不仅会给你行号,还会给你堆栈上所有可用的信息...... 我可以建议对代码编写单元测试,这样您就有了必须调试的小段代码。理想情况下,如果程序中仍然遇到未发现的错误,您甚至可以将失败情况简化为新的单元测试。

最后,性能的论证。拥有更多详细信息需要收集更多详细信息。这种收集是有代价的。在其他编程语言(如 Java(中,您可以向异常请求调用堆栈,C++,异常是最低限度的。尽管跟踪行号可能并不昂贵,但它确实需要最终用户不需要的额外组装指令。

简而言之,该语言没有提供获取行号的便捷方法。这是因为有更好的方法来获取此信息以及更多:调试器。