官术网_书友最值得收藏!

Exception filters

You can filter exceptions more easily with the when keyword. You no longer need to catch every type of exception that you are interested in and then filter it manually inside the catch block. This is a feature that was already present in VB and F#, so it's nice that C# has finally caught up.

There are some small benefits to this approach. For example, if your filter is not matched, then the exception will still be caught by other catch blocks in the same try statement. You also don't need to remember to rethrow the exception to avoid it from being swallowed. This helps with debugging, as Visual Studio will no longer break as it would when you use throw.

For example, you could check to see whether there is a message in the exception and handle it differently, as shown here:

catch (Exception e) when (e?.Message?.Length > 0)

When this feature was in development, a different keyword (if) was used. So be careful of any old information online.

One thing to keep in mind is that relying on a particular exception message is fragile. If your application is localized, then the message may be in a different language to what you expect. This holds true outside of exception filtering too.

主站蜘蛛池模板: 咸丰县| 吴川市| 五原县| 汪清县| 博爱县| 三原县| 五大连池市| 威海市| 汉源县| 女性| 尤溪县| 石渠县| 当雄县| 邵阳县| 贵州省| 瓮安县| 云林县| 博湖县| 辰溪县| 浮梁县| 桐乡市| 宁河县| 册亨县| 武宁县| 新宾| 荣昌县| 汝城县| 淳安县| 崇义县| 萨迦县| 尤溪县| 武功县| 嵊泗县| 云阳县| 景宁| 武陟县| 收藏| 桐城市| 冕宁县| 大港区| 义乌市|