catch语法之间的区别

catch语法之间的区别

本文介绍了函数的try-catch语法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了 try-catch 的语法。

struct A
{
  int a;

  A (int i) : a(i)  // normal syntax
  {
    try {}
    catch(...) {}
  }

  A ()   // something different
  try : a(0) {}
  catch(...) {}

  void foo ()  // normal function
  try {}
  catch(...) {}
};

这两种。这些语法和编码风格有什么技术上的差别吗?

Both syntax are valid. Is there any technical difference between these syntax apart from coding style ? Is one of the syntax superior to other by any aspect ?

推荐答案

第一个语法:

try块的范围在成员初始化列表完成后开始,因此在成员初始化期间抛出的任何异常都不会被此try-catch块捕获。

The First Syntax:
The scope of the try block starts after the Member Initialization list has been completed, So any exception thrown during Member Initialization will not be caught by this try-catch block.

第二种语法:

它确保如果在成员初始化列表中抛出异常,那么您可以捕获异常。

The second syntax:
It ensures that if an exception gets thrown during Member Initialization list then you are able to catch the exception.

第三个语法:

它确保从try块的起始大括号函数体被正确捕获,这意味着在参数传递期间引起的任何异常(如果发生任何异常)不会被捕获在这个try-catch块中。

The Third Syntax:
It ensures that any exception thrown from betwen the starting brace of the try block inside the function body gets caught appropriately, It would mean any exception caused during the argument passing(if any can occur) will not be caught in this try-catch block.

EDIT:

在构造函数和方法中使用第二种语法(function-try-block)时要考虑的一些指导原则析构函数:


Some guidelines to be considered while using the second syntax(function-try-block) in constructors & destructors:

根据C ++标准,

简单来说:

构造函数或析构函数 - try-block的处理程序代码必须通过发出一些异常来完成。

In Simple words:
A constructor or destructor function-try-block's handler code MUST finish by emitting some exception.

指南1:

构造函数 - try-block处理程序只有一个目的 - 翻译异常。

从析构函数中抛出异常是一个糟糕的主意,请查看 以了解原因。

指南2:

析构函数 - try-blocks没有实际用途。不应该有任何东西让他们检测,即使有东西要检测,因为邪恶的代码,处理程序不是非常有用的做任何事情,因为它不能抑制异常。

Throwing a exception from destructors is an bad idea, Take a look here to know why.
Guideline 2:
Destructor function-try-blocks have no practical use at all. There should never be anything for them to detect, and even if there were something to detect because of evil code, the handler is not very useful for doing anything about it because it can not suppress the exception.

指南3:

总是在构造函数或析构函数体中清除本地try-block处理程序中的非托管资源获取,或析构函数 - try-block处理程序。

Guideline 3:
Always clean up unmanaged resource acquisition in local try-block handlers within the constructor or destructor body, never in constructor or destructor function-try-block handlers.

对于标准风扇:

C ++标准,第15.3节第15段:

C ++标准,第15.3节第16段:






参考文献

请查看此必须阅读资源 更多详情&解释。


References:
Have a look at this must read resource here for more details & explanation.

这篇关于函数的try-catch语法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 10:39