Catch multiple exceptions at once?

前端 未结 27 2279
夕颜
夕颜 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:17

    Wanted to added my short answer to this already long thread. Something that hasn't been mentioned is the order of precedence of the catch statements, more specifically you need to be aware of the scope of each type of exception you are trying to catch.

    For example if you use a "catch-all" exception as Exception it will preceed all other catch statements and you will obviously get compiler errors however if you reverse the order you can chain up your catch statements (bit of an anti-pattern I think) you can put the catch-all Exception type at the bottom and this will be capture any exceptions that didn't cater for higher up in your try..catch block:

                try
                {
                    // do some work here
                }
                catch (WebException ex)
                {
                    // catch a web excpetion
                }
                catch (ArgumentException ex)
                {
                    // do some stuff
                }
                catch (Exception ex)
                {
                    // you should really surface your errors but this is for example only
                    throw new Exception("An error occurred: " + ex.Message);
                }
    

    I highly recommend folks review this MSDN document:

    Exception Hierarchy

提交回复
热议问题