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

前端 未结 7 986
无人共我
无人共我 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:33

    In your example, nothing, since you're not doing anything with the exception. But to clarify…

    • This catches everything but does nothing with the exception.

      catch {}
      

      This is only useful when you want to say guarantee a return from a method.

    • This catches only exceptions of type Exception (which is everything) but does nothing with the exception.

      catch (Exception) {}
      

      This is useful if you wanted to limit the type of exception being caught by specifying which types you want to handle. Any other exceptions will bubble up the call stack until a proper handler is found.

    • This catches only exceptions of type Exception (which is everything) and could do something with the exception, but happens to do nothing

      catch (Exception ex) {}
      

      This technique gives you a lot more options. You could log the exception, inspect the InnerException, etc. And again you can specify which types of exceptions you wish to handle.

    Unless you're re-throwing the exception somehow, all of these are bad practice. In general, you should only catch the exceptions you can meaningfully handle and allow anything else to bubble up.

提交回复
热议问题