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

前端 未结 7 764
无人共我
无人共我 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条回答
  •  遥遥无期
    2021-02-02 12:35

    Adding catch(Exception e) will give you access to the Exception object, which contains details about the exception that was thrown, such as its Message and StackTrace; it is useful to log this information to help diagnose bugs. A simple catch without declaring the exception that you're trying to catch won't give you access to the exception object.

    Also, catching the base Exception is generally considered bad practice because it's far too generic, and where possible you should always case for a specific exception first. For example, if you're working with files you might consider the following try/catch block:

    try{
        //open your file and read/write from it here
    }catch(FileNotFoundException fe){
        //log the message
        Log(fe.Message);
    }catch(Exception e){
        //you can catch a general exception at the end if you must
    }finally{
        //close your file
    }
    

提交回复
热议问题