Catching base Exception class in .NET

前端 未结 16 1935
心在旅途
心在旅途 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
    

提交回复
热议问题