Catching base Exception class in .NET

前端 未结 16 1923
心在旅途
心在旅途 2020-12-05 19:06

I keep hearing that

catch (Exception ex)

Is bad practise, however, I often use it in event handlers where an operation may for example go

相关标签:
16条回答
  • 2020-12-05 19:19

    I've been working a fair bit with exceptions, and here's the implementation structure I'm currently following:

    1. Dim everything to Nothing / String.Empty / 0 etc. outside of Try / Catch.
    2. Initialise everything inside Try / Catch to desired values.
    3. Catch the most specific exceptions first, e.g. FormatException but leave in base Exception handling as a last resort (you can have multiple catch blocks, remember)
    4. Almost always Throw exceptions
    5. Let Application_Error sub in global.asax handle errors gracefully, e.g. call a custom function to log the details of the error to a file and redirect to some error page
    6. Kill all objects you Dim'd in a Finally block

    One example where I thought it was acceptable to not process an exception 'properly' recently was working with a GUID string (strGuid) passed via HTTP GET to a page. I could have implemented a function to check the GUID string for validity before calling New Guid(strGuid), but it seemed fairly reasonable to:

    Dim myGuid As Guid = Nothing
    
    Try
        myGuid = New Guid(strGuid)
        'Some processing here...
    
    Catch ex As FormatException
        lblError.Text = "Invalid ID"
    
    Catch ex As Exception 
        Throw
    
    Finally
        If myGuid IsNot Nothing Then
            myGuid = Nothing
        End If
    
    End Try
    
    0 讨论(0)
  • 2020-12-05 19:20

    The bad practice is

    catch (Exception ex){}
    

    and variants:

    catch (Exception ex){ return false; }
    

    etc.

    Catching all exceptions on the top-level and passing them on to the user (by either logging them or displaying them in a message-box, depending on whether you are writing a server- or a client-application), is exactly the right thing to do.

    0 讨论(0)
  • 2020-12-05 19:24

    You should catch the exceptions related to what you are doing. If you look at the methods you call, you will see what exceptions they throw, and you want to stay more specific to those. You should have access to know what exceptions may be thrown by the methods you call, and handle them appropriately.

    And... better than having one big try catch, do your try and catch where you need the catch.

    try {
       myThing.DoStuff();
    }
    catch (StuffGoneWrongException ex) {
       //figure out what you need to do or bail
    }
    

    Maybe not quite this closely packed, but it depends on what you are doing. Remember, the job isn't just to compile it and put it on someones desktop, you want to know what breaks if something did and how to fix it. (Insert rant about tracing here)

    0 讨论(0)
  • 2020-12-05 19:25

    I think the poster is referring to exception handling like this:

    try {something} catch (SqlException) {do stuff} catch (Exception) {do other stuff}
    

    The idea here is that you want to catch the more specific errors (like SqlException) first and handle them appropriately, rather than always relying on the catch-all general Exception.

    The conventional wisdom says that this is the proper way to do exception handling (and that a solo Catch (Exception ex) is bad). In practice this approach doesn't always work, especially when you're working with components and libraries written by someone else.

    These components will often throw a different type of exception in production than the one your code was expecting based on how the component behaved in your development environment, even though the underlying problem is the same in both environments. This is an amazingly common problem in ASP.NET, and has often led me to use a naked Catch (Exception ex) block, which doesn't care what type of exception is thrown.

    Structured exception handling is a great idea in theory. In practice, it can still be a great idea within the code domain that you control. Once you introduce third party stuff, it sometimes doesn't work very well.

    0 讨论(0)
  • 2020-12-05 19:26

    No; in that case if you don't want to halt the program there's nothing else you can do and at the top level is the right place to do it, as long as you're logging properly and not hiding it away in hope grin

    0 讨论(0)
  • 2020-12-05 19:26

    This is all good of catching exceptions that you can handled. But sometimes it also happens that due to unstable environment or users just do the process correctly, the application runs into unexpected exception. Which you haven't been listed or handled in code. Is there a way that the unhandled exception is captured from app.config file and displays a common error?

    Also puts that details exception message in a log file.

    0 讨论(0)
提交回复
热议问题