What is the difference between the 3 catch block variants in C# ( 'Catch', 'Catch (Exception)', and 'Catch(Exception e)' )?

前端 未结 7 788
无人共我
无人共我 2021-02-02 11:36

In C#, what is the difference Between \'Catch\', \'Catch (Exception)\', and \'Catch(Exception e)\' ?

The MSDN article on try-catch uses 2 of them in its examples, but do

7条回答
  •  旧时难觅i
    2021-02-02 12:16

    At the highest level they are all the same; they all catch exceptions.

    But to drill down further, in the first case you are catching an exception and doing nothing with it (you don't have a defined type). In the second example, you are catching an exception of the Exception type. In your last example, you are catching the same Exception type as in example 2 but, now you are putting the exception into a variable that would allow you to show it in a MessageBox or:

    e.Message
    

    It's important to note as well that exceptions are tiered meaning, if you are catching multiple types of exceptions in the same try/catch block, you go from the most specific exception type to the most general. Like this:

    try {
    }
    catch (SqlException sqlExc) {
    }
    catch (Exception exc) {
    }
    

提交回复
热议问题