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

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 {}

?

This question is related to c#

The answer is


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!


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

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] 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?


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

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

try
{

..
..
..

}

catch(Exception ex)
{

..
..
..

}

the Exception ex means all the exceptions.


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.