简体   繁体   English

如何正确使用try-catch语句

[英]How to correctly use try-catch statement

It's been a while since my last programming excercises so here's a rather basic question. 自上次编程练习以来已经有一段时间了,所以这是一个相当基本的问题。 However I couldn't find any concrete answer yet. 但是我还没有找到具体的答案。

Let's say I have defined a method which might cause an exception. 假设我已经定义了一个可能导致异常的方法。 The method would look like this (in rather pseudo-code): 该方法看起来像这样(用伪代码表示):

public int Calculate(int x, int y) 
{
  try 
  {
    doSomeCalc();
  }
  catch (SomeException ex) 
  {
    doExceptionHandling();
  }

  return result;
}

Now if another part of the application wants to use this method should it use another try-catch block? 现在,如果应用程序的另一部分想要使用此方法,是否应该使用另一个try-catch块?

public MyMainApp() {
  try 
  {
    Calculate(1, 2);
  } 
  catch (SomeException ex) 
  {
    doExceptionHandling();
  }
}

So the question here is where should I use try-catch and where is it superfluous? 因此,这里的问题是我应该在哪里使用try-catch,它在哪里多余?

Generally, you should only use a try-catch if there is something that you can do in the catch. 通常,只有在捕获中可以执行某些操作时,才应使用try-catch。 Can you retry the failed connection or otherwise help the user to continue? 您可以重试失败的连接还是以其他方式帮助用户继续? Do you want to log the exception? 您是否要记录例外?

If there's nothing you can do to recover or gracefully degrade, there is no point in catching the exception. 如果您无法采取任何措施来恢复或正常降级,则捕获异常是没有意义的。 Just let it bubble up to a catch at the top of the app (for example, in the Page_Error event in the base page of a web app) and handle the UI there. 只需让它冒出到应用程序顶部的陷阱(例如,在Web应用程序基本页面的Page_Error事件中)并在那里处理UI。

If Calculate already catches the exception and handles it, why should MyMainApp care about it at all? 如果Calculate已经捕获并处理了异常,为什么MyMainApp应该MyMainApp关心它? If it does not catch it, MyMainApp might want to handle it. 如果未捕获,则MyMainApp可能要处理它。 It should not catch it if it doesn't handle it in a useful way(at least log the exception). 如果不能以一种有用的方式处理它 (至少记录异常), 它就不会捕获它

Best-practise is to throw meaningful exceptions as soon as possible, eg(assuming that negative values can cause wrong results or exceptions): 最佳实践是尽快抛出有意义的异常,例如(假设负值可能导致错误的结果或异常):

public int Calculate(int x, int y)
{
    if (x <= 0)
        throw new ArgumentException("X has to be positive", "x");
    if (y <= 0)
        throw new ArgumentException("Y has to be positive", "y");

    // now the calculation should be safe without any side-effects
    // ...
}

It depends on the SomeException type. 它取决于SomeException类型。 If it is the base class of all exceptions, no, it is not needed in your second block. 如果它是所有异常的基类,则否,在第二个块中不需要它。 However, if it processes only one specific type of exception and it is possible for others to occur, you need a second block. 但是,如果它仅处理一种特定类型的异常,并且有可能发生其他异常,则需要第二个块。 Why would you need to process only one specific exception? 为什么只需要处理一个特定的异常? That is for you to find out, if needed :) 如果需要的话,这是供您查找的:

The rule of thumb is that you only catch where you are going to do something with the exception. 经验法则是,除了例外情况,您只能捕获将要执行操作的位置。 For example, logging a particular exception or retrying the call. 例如,记录特定的异常或重试呼叫。

In order to maintain the stack trace, you usually re-throw the exception using throw; 为了维护堆栈跟踪,通常使用throw;重新抛出异常throw; and then have some mechanism at the top of the process that globally handles errors. 然后在流程的顶部设置某种机制来全局处理错误。

In general, try-catch should be used when you need to handle error cause by certain statement execution. 通常,当您需要处理由某些语句执行引起的错误时,应使用try-catch。

For example, In case of Db connectivity, SqlException is raised that can have information related to the error, like Wrong Password , Invalid Database ... 例如,在Db连接的情况下,将引发SqlException ,该异常可能具有与错误相关的信息,例如Wrong PasswordInvalid Database

try
{
    //try connect to db
}
catch (SqlException ex)
{
    // information of database related exception
}
catch (Exception ex)
{
    // catch any other error
}

Exception Handling at time is not as simple as it seems. 当时的Exception Handling并不像看起来那样简单。

Please read this article (I personally have learnt a lot from it ) : Exception Handling Best Practices in .NET 请阅读这篇文章(我个人已经从中学到了很多东西) :.NET中的异常处理最佳实践

Try putting try and catch inside event functions since normal functions would be called from event functions only.And only use try in other layer functions if some rollbacks are to be performed. 尝试将try and catch放入event functions内部,因为仅会从事件函数调用普通函数,并且仅在要执行某些rollbacks情况下在其他层函数中使用try。 Hope it helps.... 希望能帮助到你....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM