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

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.

主站蜘蛛池模板: 卢氏县| 鄱阳县| 郓城县| 清徐县| 绥阳县| 喀喇沁旗| 龙门县| 金阳县| 德格县| 乃东县| 弥勒县| 个旧市| 白城市| 宽城| 尼勒克县| 柯坪县| 台湾省| 新源县| 密云县| 遂平县| 永州市| 鲁山县| 南汇区| 江口县| 罗源县| 鲜城| 台前县| 湘西| 绥阳县| 张北县| 兴山县| 中卫市| 上林县| 卢龙县| 荣成市| 锦屏县| 进贤县| 华池县| 苏尼特右旗| 疏勒县| 乌恰县|