C# 中的异常处理:Multple Try/Catches vs. One
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/372282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Exception Handling in C#: Multple Try/Catches vs. One
提问by Miyagi Coder
Is it good practice to have more than one try{} catch{}
statement per method?
try{} catch{}
每个方法有多个语句是一种好习惯吗?
采纳答案by Brian Rasmussen
In my point of view it is good practice to have each method handle only a single task. As such you'll rarely need to have multiple try/catch blocks within a single method. However, I don't see any problems with it.
在我看来,让每个方法只处理一个任务是一种很好的做法。因此,您很少需要在一个方法中包含多个 try/catch 块。但是,我认为它没有任何问题。
As Lisa pointed out you should catch specific exceptions and onlycatch the exceptions the method can actually handle.
正如 Lisa 指出的那样,您应该捕获特定的异常,并且只捕获该方法实际可以处理的异常。
回答by l15a
It's better to have one try/catch with multiple catches to handle each type of Exception differently.
最好有一个带有多个捕获的 try/catch 来以不同的方式处理每种类型的异常。
回答by Kekoa
I would say that depends. To me, it looks a little sloppy having all these try-catches everywhere. I try to consolidate to a try block with many catches. Sometimes this doesn't work, you may need to have them separate, but to keep things readable, that's how I prefer it at least.
我会说这取决于。对我来说,到处都是这些尝试捕获的东西看起来有点草率。我尝试合并到一个有很多捕获的 try 块。有时这不起作用,您可能需要将它们分开,但为了保持可读性,至少我更喜欢这样。
Also if your method is too long of course, you can extract methods to distribute your try catching.
此外,如果您的方法当然太长,您可以提取方法来分发您的尝试捕获。
回答by Bullines
If you know the type of Exceptions that could occur beforehand, you can have a single try and catch each of those exceptions, should you want to handle them differently. For example:
如果您事先知道可能发生的异常类型,您可以尝试一次并捕获每个异常,如果您想以不同的方式处理它们。例如:
try
{
// a bunch of risky code
}
catch (SpecificException1 ex1)
{
// handle Specific Exception 1
}
catch (SpecificException2 ex2)
{
// handle Specific Exception 2
}
catch (SpecificException3 ex3)
{
// handle Specific Exception 3
}
catch (Exception ex)
{
// handle an exception that isn't specific
}
回答by Andy Webb
It depends. The purpose of exception handling is just that, handling run time exceptions when they occur.
这取决于。异常处理的目的只是,在它们发生时处理运行时异常。
I typically have one catch all try/catch and then I place try catch blocks around areas of code I know have the potential to throw exceptions (type conversions, etc).
我通常有一个 catch all try/catch 然后我在我知道有可能抛出异常(类型转换等)的代码区域周围放置 try catch 块。
回答by Marc Gravell
Generally, I tend to have a lot more finally
than catch
. Usually, there isn't much specificyou can do with an exception, so let it bubble. But the finally
ensures you can close things down cleanly etc.
一般来说,我倾向于拥有finally
比catch
. 通常情况下,没有太多具体的你可以用一个例外做的,所以让它的泡沫。但是finally
可以确保您可以干净地关闭东西等。
回答by Bent André Solheim
I find consolidating many lines of code that each can throw their own exception into one try block with many catches makes the code hard to read. It's not apparent from just looking at the code what line of code throws what exception. In my opinion, try catches should contain as little code as possible; only the code that can throw the given exception. If the method you are writing contains more than a few try catches, they should each be extracted into their own methods.
我发现将多行代码合并在一起,每一行都可以将自己的异常抛出到一个带有许多捕获的 try 块中,这使得代码难以阅读。仅查看代码并不清楚哪行代码会引发什么异常。在我看来,try catch 应该包含尽可能少的代码;只有可以抛出给定异常的代码。如果您正在编写的方法包含多个尝试捕获,则应将每个捕获到自己的方法中。
This becomes more important if you have more than one method call in your method that throws the same exception. Then they really should be in separate try catches, because when you catch the exception, you generally want to wrap it in a new exception appropriate for the current abstraction with a relevant error message. If you have both statements in the same try catch, you lose the opportunity to give different error messages for the different errors.
如果您的方法中有多个方法调用会引发相同的异常,这将变得更加重要。那么它们真的应该在单独的 try catch 中,因为当您捕获异常时,您通常希望将它包装在一个适合当前抽象的新异常中,并带有相关的错误消息。如果您在同一个 try catch 中有两个语句,您将失去为不同错误提供不同错误消息的机会。
Object operationResult;
try {
operationResult = remoteService.performRemoteOperation();
} catch (RemoteException ex) {
throw new BusinessException("An error occured when getting ...", ex);
}
// use operation result
回答by BenAlabaster
As a rule of thumb, each method should process a single task - this best practice is derived from a test driven environment which makes it far easier to generate tests. It's inherently more difficult to write a test plan for "god" procedures.
根据经验,每种方法都应该处理一个任务——这个最佳实践源自测试驱动的环境,这使得生成测试变得更加容易。为“上帝”程序编写测试计划本身就更加困难。
It is also therefore a best practice to only use try{} catch{} around items that could fail and only where you would normally catch the exception for useful processing.
因此,最佳做法也是仅在可能失败的项目周围使用 try{} catch{},并且仅在您通常会捕获异常以进行有用处理的地方使用。
Don't use a single try{} catch{} to wrap the entire content of your method thus removing responsibility for decent coding practices.
不要使用单个 try{} catch{} 来包装您的方法的全部内容,从而免除对体面编码实践的责任。
It is an expensive operation to process exceptions - catch them where necessary and write code that would prevent exceptions occurring elsewhere. There are occasions where it's not inherently simple to prevent an exception, but it can be caught and used productively using a try/catch - for instance checking for exclusivity on file operations.
处理异常是一项昂贵的操作 - 在必要时捕获它们并编写代码以防止在其他地方发生异常。在某些情况下,防止异常本身并不简单,但可以使用 try/catch 捕获并有效地使用它 - 例如检查文件操作的排他性。
Make a conscious decision when you use the try/catch, don't just throw it in because you can, that's lazy. Ask yourself "do I need it here?", or "can I do this using a less expensive and/or a more structured approach?".
当你使用 try/catch 时要有意识地做出决定,不要因为你可以就扔掉它,那是懒惰的。问问自己“我在这里需要它吗?”,或者“我可以使用更便宜和/或更结构化的方法来做到这一点吗?”。
回答by Sara Chipps
IMO if you know the exception that might happen before hand you shouldn't use try...catch to get the error.
IMO 如果您事先知道可能发生的异常,则不应使用 try...catch 来获取错误。
don't program with exceptions.... so I don't think multiples is a good idea.
不要在例外情况下编程......所以我认为倍数不是一个好主意。
回答by Robert Rossney
The merit of using multiple try/catch blocks is that it clearly pairs the operation you're attempting with the expected exception. Generally speaking, you're not going to catch an exception if the condition that threw it is unrecoverable (unless you're doing something like logging specific exceptions for diagnostics). Code like this:
使用多个 try/catch 块的优点是它清楚地将您尝试的操作与预期的异常配对。一般来说,如果抛出异常的条件不可恢复,您将不会捕获异常(除非您正在执行诸如记录特定异常以进行诊断之类的操作)。像这样的代码:
try
{
Operation1();
}
catch (MySpecificException1)
{
RecoverFromExpectedException1();
}
try
{
Operation2();
}
catch (MySpecificException2)
{
RecoverFromExpectedException2();
}
may be a little verbose, but that's a consequence of using exceptions for flow control. The important thing is you can tell by looking at this code that the first operation may throw an specific exception, and that your code knows how to recover from this exception and move on to the second operation. And the try/catch blocks aren't doing anything else butthat.
可能有点冗长,但这是使用异常进行流控制的结果。重要的是,您可以通过查看此代码看出第一个操作可能引发特定异常,并且您的代码知道如何从该异常中恢复并继续执行第二个操作。而try / catch块没有做别的事情,但是这一点。