Catch multiple exceptions at once?

前端 未结 27 1882
夕颜
夕颜 2020-11-22 11:31

It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecce

27条回答
  •  北海茫月
    2020-11-22 12:15

    It is worth mentioning here. You can respond to the multiple combinations (Exception error and exception.message).

    I ran into a use case scenario when trying to cast control object in a datagrid, with either content as TextBox, TextBlock or CheckBox. In this case the returned Exception was the same, but the message varied.

    try
    {
     //do something
    }
    catch (Exception ex) when (ex.Message.Equals("the_error_message1_here"))
    {
    //do whatever you like
    } 
    catch (Exception ex) when (ex.Message.Equals("the_error_message2_here"))
    {
    //do whatever you like
    } 
    

提交回复
热议问题