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

前端 未结 7 935
无人共我
无人共我 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条回答
  •  Happy的楠姐
    2021-02-02 12:26

    All of them do basically the same thing, the difference being the amount of information they provide about the error.

    catch (foo ex) {} will filter out all exceptions, except those that can be cast to type foo. It also gives you the instance of the error for you to work on.

    catch (foo) {} does the same as above, but it doesn't give you the instance of the exception. You'll know the type of the exception, but won't be able to read information from it.

    Notice that in both of those cases, if the type of the exception is Exception, they'll catch all exceptions.

    catch {} catches all exceptions. You don't know the type it caught and you can't access the instance.

    You can choose which one to use based on how much information you need from the exception should it be caught.

    Regardless of which one you use, you can pass the caught exception forward by using the command throw; (without arguments).

提交回复
热议问题