有些帖子询问这两者之间的区别是什么.
(为什么我还要提这个...)
但我的问题是不同的,我称之为"抛出前"在另一个错误的神像处理方法.
public class Program {
public static void Main(string[] args) {
try {
// something
} catch (Exception ex) {
HandleException(ex);
}
}
private static void HandleException(Exception ex) {
if (ex is ThreadAbortException) {
// ignore then,
return;
}
if (ex is ArgumentOutOfRangeException) {
// Log then,
throw ex;
}
if (ex is InvalidOperationException) {
// Show message then,
throw ex;
}
// and so on.
}
}
Run Code Online (Sandbox Code Playgroud)
如果try & catch用于Main,那么我会throw; …
我想知道将异常从一种方法传递给另一种方法的正确方法是什么.
我正在开发一个分为Presentation(web),Business和Logic层的项目,并且需要在链中传递错误(例如SqlExceptions)以在出现问题时通知Web层.
我见过3种基本方法:
try
{
//error code
}
catch (Exception ex)
{
throw ex;
}
Run Code Online (Sandbox Code Playgroud)
(只是重新抛出)
try
{
//error code
}
catch (Exception ex)
{
throw new MyCustomException();
}
Run Code Online (Sandbox Code Playgroud)
(抛出自定义异常,以便不传递对数据提供程序的依赖关系)
然后简单地说
//error code
Run Code Online (Sandbox Code Playgroud)
(根本不做任何事情,让错误自己冒出来)
当然,catch块中也会发生一些日志记录.
我更喜欢3号,而我的同事使用方法1,但我们都不能真正激励为什么.
使用每种方法有哪些优点/缺点?有一种我不知道的更好的方法吗?有没有被接受的最佳方式?