c# - 如何使用try和catch捕获c#中的所有异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12911833/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:56:51  来源:igfitidea点击:

How to catch all exceptions in c# using try and catch?

c#

提问by Gorden Gram

I want to write some try and catch that catch any type or exception, is this code is enough (that's the way to do in Java)?

我想写一些 try 和 catch 来捕获任何类型或异常,这段代码是否足够(这是在 Java 中的做法)?

try {
code....
}
catch (Exception ex){}

Or should it be

或者应该是

try {
code....
}
catch {}

?

?

采纳答案by Mark Byers

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because exis declared but not used.

这两种方法都会捕获所有异常。您的两个代码示例之间没有显着差异,只是第一个将生成编译器警告,因为ex已声明但未使用。

But note that some exceptions are special and will be rethrown automatically.

但请注意,有些异常是特殊的,会自动重新抛出。

ThreadAbortExceptionis a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

ThreadAbortException是一个可以被捕获的特殊异常,但它会在 catch 块的末尾自动再次引发。

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx



As mentioned in the comments, it is usually a very bad ideato catch and ignore all exceptions. Usually you want to do one of the following instead:

正如评论中提到的,捕获并忽略所有异常通常是一个非常糟糕的主意。通常,您希望执行以下操作之一:

  • Catch and ignore a specific exception that you know is not fatal.

    catch (SomeSpecificException)
    {
        // Ignore this exception.
    }
    
  • Catch and log all exceptions.

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    
  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch
    {
        SomeCleanUp();
        throw;
    }
    
  • 捕获并忽略您知道不是致命的特定异常。

    catch (SomeSpecificException)
    {
        // Ignore this exception.
    }
    
  • 捕获并记录所有异常。

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    
  • 捕获所有异常,进行一些清理,然后重新抛出异常。

    catch
    {
        SomeCleanUp();
        throw;
    }
    

Note that in the last case the exception is rethrown using throw;and not throw ex;.

请注意,在最后一种情况下,使用throw;和 not 重新抛出异常throw ex;

回答by RvdK

Both are fine, but only the first one will allow you to inspect the Exception itself.

两者都很好,但只有第一个允许您检查异常本身。

Both swallow the Exception, and you should only catch exceptions to do something meaningfull. Hiding a problem is notmeaningful!

两者都吞下异常,你应该只捕获异常来做一些有意义的事情。隐藏问题没有意义!

回答by Dejo

Both ways are correct.

两种方式都是正确的。

If you need to do something with the Exception object in the catch block then you should use

如果您需要对 catch 块中的 Exception 对象执行某些操作,那么您应该使用

try {
    // code....
}
catch (Exception ex){}

and then use exin the catch block.

然后ex在 catch 块中使用。

Anyway, it is not always a good practice to catch the Exception class, it is a better practice to catch a more specific exception - an exception which you expect.

无论如何,捕获 Exception 类并不总是一个好习惯,捕获一个更具体的异常是一个更好的做法 - 您期望的异常。

回答by matthid

Note that besides all other comments there is a small difference, which should be mentioned here for completeness!

请注意,除了所有其他评论之外,还有一个小差异,为了完整起见,应在此处提及!

With the empty catch clause you can catch non-CLSCompliant Exceptions when the assembly is marked with "RuntimeCompatibility(WrapNonExceptionThrows = false)" (which is true by default since CLR2). [1][2][3]

使用空 catch 子句,当程序集标记为“RuntimeCompatibility(WrapNonExceptionThrows = false)”(自 CLR2 以来默认为 true)时,您可以捕获非 CLSCompliant 异常。[1][2][3]

[1] http://msdn.microsoft.com/en-us/library/bb264489.aspx

[1] http://msdn.microsoft.com/en-us/library/bb264489.aspx

[2] http://blogs.msdn.com/b/pedram/archive/2007/01/07/non-cls-exceptions.aspx

[2] http://blogs.msdn.com/b/pedram/archive/2007/01/07/non-cls-exceptions.aspx

[3] Will CLR handle both CLS-Complaint and non-CLS complaint exceptions?

[3] CLR 是否会同时处理 CLS 投诉和非 CLS 投诉异常?

回答by Arun Prasad E S

I catch all the exceptions and store it in database, so errors can be corrected easily - the page, place, date etc stored

我捕获所有异常并将其存储在数据库中,因此可以轻松更正错误 - 存储的页面、地点、日期等

try
{     
   Cart = DB.BuyOnlineCartMasters.Where(c => c.CmpyID == LoginID && c.Active == true).FirstOrDefault();
}
catch (Exception e)
{
    ErrorReport.StoreError("CartMinifiedPartial-Company", e);  
    -- storing the error for reference
}

Storing

收藏

public static void StoreError(string ErrorPage, Exception e)
    {
        try
        {
            eDurar.Models.db_edurarEntities1 DB = new Models.db_edurarEntities1();
            eDurar.Models.ErrorTable Err = new eDurar.Models.ErrorTable();
            Err.ErrorPage = ErrorPage;
            if (e.Message != null)
            {
                Err.ErrorDetails = e.Message;
            }
            if (e.InnerException != null)
            {
                Err.InnerException = e.InnerException.Message.ToString();
            }

            Err.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
            DB.ErrorTables.AddObject(Err);
            DB.SaveChanges();
}

回答by Reza Mahmoodi

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    }

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        throw new NotImplementedException();
    }

回答by zzz

try
{

..
..
..

}

catch(Exception ex)
{

..
..
..

}

the Exception ex means all the exceptions.

Exception ex 表示所有的异常。