本文介绍了在总结的try-catch或代码的特定部分的所有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的资深同事告诉我包装一个try-catch块中的每一个方法,使他们能够追踪到异常发生时帮助调试问题更​​快。它是更好地包装在一个尝试捕捉每一个方法,如这:

My senior colleague tells me to wrap every method within a try-catch block so they can trace where exceptions occurs to help debug issues quicker. Is it better to wrap every method in a Try Catch such as this to:

Public int foo()
{
   try
   {
       //do something
   }catch(Exeception ex)
   {
       //do something with ex
   }
}

或者是还好赶上,我认为可能会出现异常,他们?例如。做一些与阵列可能会导致 IndexOutOfRangeException 将出现。

Or is it better to catch exceptions where I think they may occur? E.g. doing something with an array may cause the IndexOutOfRangeException will occur.

//wrap this in try catch
    int[] array = new int[3];

                array[0] = 1;
                array[1] = 2;
                array[2] = 3;
                array[3] = 4;



感谢。

Thanks.

推荐答案

该try块包含了保护代码可能会导致异常。执行该块,直到抛出一个异常,或者成功完成。

The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully.

您可以看看在

根据经验,捕获异常的基本规则是捕捉异常,当且仅当你有处理这些有意义的方式。

The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.

如果你只是要记录异常并把它堆栈不要捕捉异常。也是没有意义和杂波的代码。

Don't catch an exception if you're only going to log the exception and throw it up the stack. It serves no meaning and clutters code.

不要捕捉异常,当你在你的代码中的特定部分预期失败,如果你有这方面的后备。

Do catch an exception when you are expecting a failure in a specific part of your code, and if you have a fallback for it.

当然,你总是有检查异常需要您使用try / catch块,在这种情况下,你没有其他选择的情况下。即使是检查的异常,请确保您正确登录并尽可能干净处理。

Of course you always have the case of checked exceptions which require you to use try/catch blocks, in which case you have no other choice. Even with a checked exception, make sure you log properly and handle as cleanly as possible.

这篇关于在总结的try-catch或代码的特定部分的所有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 09:42