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

C#Exception

C# Problem Overview


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 {
code....
}
catch (Exception ex){}

Or should it be

try {
code....
}
catch {}

?

C# Solutions


Solution 1 - C#

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 ex is declared but not used.

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

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

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


As mentioned in the comments, it is usually a very bad idea to 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;
     }
    

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

Solution 2 - C#

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]

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

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

[3] https://stackoverflow.com/questions/1531077/will-clr-handle-both-cls-complaint-and-non-cls-complaint-exceptions

Solution 3 - C#

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();
}

Solution 4 - C#

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

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

Solution 5 - C#

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 not meaningful!

Solution 6 - C#

Both ways are correct.

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

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

and then use ex in the catch block.

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.

Solution 7 - C#

try
{

..
..
..

}

catch(Exception ex)
{

..
..
..

}

the Exception ex means all the exceptions.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGorden GramView Question on Stackoverflow
Solution 1 - C#Mark ByersView Answer on Stackoverflow
Solution 2 - C#matthidView Answer on Stackoverflow
Solution 3 - C#Arun Prasad E SView Answer on Stackoverflow
Solution 4 - C#Reza MahmoodiView Answer on Stackoverflow
Solution 5 - C#RvdKView Answer on Stackoverflow
Solution 6 - C#DejoView Answer on Stackoverflow
Solution 7 - C#zzzView Answer on Stackoverflow