Gorden Gram
Gorden Gram

Reputation: 981

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

?

Upvotes: 73

Views: 159910

Answers (8)

Reza Mahmoodi
Reza Mahmoodi

Reputation: 706

Catch global all exceptions in app

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

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

Upvotes: 3

matthid
matthid

Reputation: 1704

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

Upvotes: 9

Pronner
Pronner

Reputation: 25

If you're looking to catch ALL EXCEPTIONS in the application, You can write:

try
{

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new YourFormName());

}
catch (Exception ex) // This is optional if you want to display the exception
{

    MessageBox.Show(ex.ToString()); // using the "ex" defined in the catch phrase to show the exception in a message box, again, optional if you do not want to show the issue.

}

in the Program.cs file. This way, every exception in the application will be handled inside the brackets of the catch phrase.

Upvotes: 0

zzz
zzz

Reputation: 1

try
{

..
..
..

}

catch(Exception ex)
{

..
..
..

}

the Exception ex means all the exceptions.

Upvotes: -2

Dejo
Dejo

Reputation: 2148

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.

Upvotes: 0

Arun Prasad E S
Arun Prasad E S

Reputation: 10115

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

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 838006

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;.

Upvotes: 94

RvdK
RvdK

Reputation: 19790

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!

Upvotes: 2

Related Questions