What is the best alternative “On Error Resume Next” for C#?

后端 未结 11 2823
南方客
南方客 2021-02-19 08:12

If I put empty catch blocks for my C# code, is it going to be an equivalent for VB.NET\'s \"On Error Resume Next\" statement.

try
{
    C# code;
}

catch(excepti         


        
11条回答
  •  忘掉有多难
    2021-02-19 08:38

    I am an old hat at VB6. First a short lesson...

    There are reasons to use On Error Resume Next. Mostly for readability. In VB6 you have two ways to implement Error trapping. You can use an "inline" On Error Resume Next like this.

    On Error Resume Next
    
    If Err.Number <> 0 Then
       
       Err.Clear()
    End If
    

    Or, you may see this:

    Sub DoSomething
    
       On Error Goto Handler1
       
    
       On Error Goto Handler2
       
    
       Exit Sub
    
       Handler1:
       
       Resume Next
    
       Handler2:
       
       Resume Next
    
    End Sub  
    

    But in old VB6 code you will likely also see this...

    Sub PerformThis
    On Error Resume Next
    
    End Sub
    

    Regardless it is pretty straight forward to convert these cases into Try Catch... If you need to sink an error use a quick "inline" looking On Error Resume Next just do this..

    try { _objectinfo.Add(_object.attribute1); } catch (Exception _e) { }
    

    You can also raise the try catch to the calling routine, by encapsulating the code into a subroutine... So if you need to sink the entire subroutine do this...

    try { PerformAction(); } catch (Exception _e) { }
    

    Do this in the case where PerformAction() subroutine contains an On Error Resume Next at the top of the code, use the Try Catch in the calling subroutine

    Good luck...

提交回复
热议问题