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

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.

主站蜘蛛池模板: 沁源县| 武鸣县| 浑源县| 四子王旗| 东丰县| 化隆| 曲水县| 泰州市| 常宁市| 广灵县| 连云港市| 清镇市| 静海县| 溧阳市| 永州市| 刚察县| 滦平县| 洞头县| 平武县| 友谊县| 内乡县| 囊谦县| 馆陶县| 农安县| 滦平县| 项城市| 彭州市| 台北县| 灵台县| 岫岩| 西吉县| 勐海县| 临桂县| 巴林左旗| 肃宁县| 吴旗县| 绥德县| 潼南县| 漳州市| 启东市| 鱼台县|