- ASP.NET Core 2 High Performance(Second Edition)
- James Singleton
- 214字
- 2021-07-08 09:38:58
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.
- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- C#完全自學(xué)教程
- Nexus規(guī)模化Scrum框架
- 網(wǎng)絡(luò)爬蟲原理與實(shí)踐:基于C#語言
- Learning Python by Building Games
- Struts 2.x權(quán)威指南
- Python計(jì)算機(jī)視覺和自然語言處理
- Visual Basic程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo)及考試指南
- Java程序設(shè)計(jì)教程
- 寫給青少年的人工智能(Python版·微課視頻版)
- IBM RUP參考與認(rèn)證指南
- Learning Ionic(Second Edition)
- Manage Your SAP Projects with SAP Activate
- R語言數(shù)據(jù)分析從入門到實(shí)戰(zhàn)
- AngularJS by Example