In C#, how do I know which exceptions to catch?

前端 未结 11 1350
抹茶落季
抹茶落季 2020-12-30 08:33

I\'ve gotten in the habit of using a general catch statement and I handle those exceptions in a general manner. Is this bad practice? If so, how do I know which specific exc

11条回答
  •  萌比男神i
    2020-12-30 09:17

    The bigger question is if you need to do specific error handling on specific exceptions. If you just need to catch any errors that occur, there is nothing wrong with just making a generic try/catch block:

    try
    {
        // Some Code
    }
    catch
    {
    }
    

    However, if you need do specific handling on certain exceptions, you can specify multiple catch blocks per a single try:

    try
    {
        // Some Code
    }
    catch(ArgumentException argE)
    {
    }
    catch(NullReferenceException nullE)
    {
    }
    catch(Exception e)
    {
        // Everything else
    }
    

    If you can't recover from an exception, don't catch it at that level.

提交回复
热议问题