在 try 块中应该只有可以抛出异常的指令或者可以放置一些与异常无关的代码?

Inside a try block should only be the instructions that could throw the exception or can put some code not relevant for the exception?

如果我知道只有一个函数(以示例为例)会抛出异常,那么以下选项的正确方法是什么?

  1. 全部在 try 块中:

    try
    {
        while (someCondition)
        {
            take();   
            anotherFunction();
        }
    }
    catch(Exceotion e)
    {
        //some instructions
    }
    
  2. 块内只有抛出异常的函数:

    while (someCondition)
        {
            try
            { 
                take();   
            }
            catch....
            {
                 //some instructions
            }
            anotherFunction();
        }       
    

我会使用第一种方式,因为它更清晰,但是对此有明确的规定吗?

谢谢!

这两种方式 非常 不同的事情,取决于你需要代码做什么,任何一种都是正确的。

在第一个示例中,如果出现异常则不会调用 anotherFunction

第二个例子,异常在catch块中处理,anotherFunction会在后面执行。

按照相同的思路,在第一个示例中,异常中止了整个 while 循环,而在第二个示例中,它仅中止了一次迭代并在下一次迭代中继续循环。