在C ++中调度异常 [英] Dispatching exceptions in C++

查看:165
本文介绍了在C ++中调度异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何调度异常,以便以集中,用户友好的方式处理错误处理和诊断?

How should exceptions be dispatched so that error handling and diagnostics can be handled in a centralized, user-friendly manner?

例如:


  • DataHW类处理与某些数据采集硬件的通信。

  • DataHW类可能会基于一些可能的错误:间歇信号,无信号,CRC故障,驱动器错误。

  • DataHW类由许多不同的代码块调用,这些代码具有不同的获取和分析类型。

正确的错误处理策略取决于异常的类型和尝试的操作。 (在间歇信号,重试X次然后告诉用户;在驱动程序错误,记录错误和重新启动驱动程序等)。应如何调用此错误处理策略?

The proper error handling strategy depends on the type of exception and the operation being attempted. (On intermittent signal, retry X times then tell the user; on a driver error, log an error and restart the driver; etc.) How should this error handling strategy be invoked?


  • 将错误恢复到每个异常类中:这将导致异常类非常大,并包含高级UI和系统管理代码。

  • 为每种类型的异常提供单独的 catch 块:因为DataHW类是从许多不同的地方调用的,每个 catch 块将必须在每个调用站点重复。 c> 函数与一个基于RTTI的开关语句:RTTI和 switch 通常表示未能应用OO设计,似乎是最不好的替代方案。

  • Coding error recovery into each exception class: This would result in exception classes that are rather large and contain high-level UI and system management code. This seems bad.
  • Providing a separate catch block for each type of exception: Since the DataHW class is called from many different places, each catch block would have to be duplicated at each call site. This seems bad.
  • Using a single catch block that calls some ExceptionDispatch function with a giant RTTI-based switch statement: RTTI and switch usually indicates a failure to apply OO design, but this seems the least bad alternative.

推荐答案

避免在每个调用站点重复catch块(...)并调用重新抛出和分派的共享处理函数:

Avoid duplicating the catch blocks at each call site by catching (...) and calling a shared handler function which rethrows and dispatches:

f()
{
    try
    {
        // something
    }
    catch (...)
    {
        handle();
    }
}

void handle()
{
    try
    {
        throw;
    }
    catch (const Foo& e)
    {
        // handle Foo
    }
    catch (const Bar& e)
    {
        // handle Bar
    }
    // etc
}

这篇关于在C ++中调度异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆