C# 6.0 (C# vNext) 新功能之:Exception-Handling Improvements
2014-10-14 21:33
453 查看
在 C# 6.0 新功能裹的异常处理,有两个改进:
异步处理(async and await)可以在 catch block 裹使用了。在 C# 5.0 推出的 async and await,当时不可以用於 catch block,现在已经可以了。
支持异常过滤 exception filtering
异步处理的例子:
异常过滤,这算是让 C# 跟上 Visual Basic .NET 和 F# 在这方面的支持。
如下例子:
比较一下之前的写法:
异步处理(async and await)可以在 catch block 裹使用了。在 C# 5.0 推出的 async and await,当时不可以用於 catch block,现在已经可以了。
支持异常过滤 exception filtering
异步处理的例子:
try { WebRequest webRequest = WebRequest.Create("http://www.csdn.net"); WebResponse response = await webRequest.GetResponseAsync(); // ... } catch (WebException exception) { await WriteErrorToLog(exception); }
异常过滤,这算是让 C# 跟上 Visual Basic .NET 和 F# 在这方面的支持。
如下例子:
try { DoSomeHttpRequest(); } catch (System.Web.HttpException e) if (e.GetHttpCode() == 400) { WriteLine("Not Found"); } catch (System.Web.HttpException e) if (e.GetHttpCode() == 500) { WriteLine("Internal Server Error"); } catch { WriteLine("Generic Error"); }
比较一下之前的写法:
try { DoSomeHttpRequest(); } catch (System.Web.HttpException e) { switch (e.GetHttpCode()) { case 400: WriteLine("Bad Request"); case 500: WriteLine("Internal Server Error"); default: WriteLine("Generic Error"); } }
相关文章推荐
- C# 6.0 (C# vNext) 的新功能:Exception-Handling Improvements
- C# 6.0 (C# vNext) 新功能之:Event initializers
- C# 6.0 (C# vNext) 新功能之:Expression Bodied Functions and Properties
- C# 6.0 (C# vNext) 新功能之:Static Using Statements
- C# 6.0 (C# vNext) 新功能之:Auto-Properties with Initializers
- C# 6.0 (C# vNext) 新功能之:Nameof Expressions
- C# 6.0 (C# vNext) 新功能之:Null-Conditional Operator
- C# 6.0 (C# vNext) 新功能之:Semicolon operator
- C# 6.0 (C# vNext) 新功能之:Primary Constructors 主要的构造函式
- C# 6.0 (C# vNext) 的新功能:Expression Bodied Functions and Properties
- C# 6.0 (C# vNext) 新功能之:Numeric Literal Formats
- C# 6.0 (C# vNext) 新功能之:Indexed Members and Element Initializers 索引的成員和元素初始化
- C# 6.0 (C# vNext) 新功能之:Declaration Expressions
- C#note 05: Errors and Exception Handling
- Exception handling with custom error pages in ASP.NET using C#.
- C#编程.异常处理(Exception Handling Statements)
- Exception handling in X++ and C#
- C# 6.0 的新功能
- Exception Handling in C#
- C# Exception Handling