search

C# exception enhancement

Mar 12, 2017 pm 03:45 PM
c#

0. Catalog

C#6 NewFeature Catalog

1. In the catch and finally blocks Using await

introduces a pair of keywords await/async in C#5 to support the new asynchronousProgramming model, making C# asynchronous programming The model is further simplified (APM->EAP->TAP->await/async. The asynchronous programming model in C# is not the Introduction focus of this article. For detailed information, please go here Asynchronous Programming Pattern). Although await/async was introduced in C#5, it has some restrictions. For example, it cannot be used in catch and finally statement blocks. This restriction will no longer apply in C#6.


 1 using System; 2 using System.Threading; 3 using System.Threading.Tasks; 4  5 namespace csharp6 6 { 7     internal class Program 8     { 9         private static void Main(string[] args)10         {11             do12             {13                 Log(ConsoleColor.White, "caller method begin", true);14                 CallerMethod();15                 Log(ConsoleColor.White, "caller method end");16             } while (Console.ReadKey().Key != ConsoleKey.Q);17         }18 19         public static async void CallerMethod()20         {21             try22             {23                 Log(ConsoleColor.Yellow, "try ", true);24                 throw new Exception();25             }26             catch (Exception)27             {28                 Log(ConsoleColor.Red, "catch await begin", true);29                 await AsyncMethod();30                 Log(ConsoleColor.Red, "catch await end");31             }32             finally33             {34                 Log(ConsoleColor.Blue, "finally await begin", true);35                 await AsyncMethod();36                 Log(ConsoleColor.Blue, "finally await end");37             }38         }39 40         private static Task AsyncMethod()41         {42             return Task.Factory.StartNew(() =>43             {44                 Log(ConsoleColor.Green, "async method begin");45                 Thread.Sleep(1000);46                 Log(ConsoleColor.Green, "async method end");47             });48         }49 50         private static void Log(ConsoleColor color, string message, bool newLine = false)51         {52             if (newLine)53             {54                 Console.WriteLine();55             }56             Console.ForegroundColor = color;57             Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");58         }59     }60 }

The running results are as follows:

If you are careful, you will find thatasync method begin:6The color of this line is not the green I set, but white, and the order is also out of order; if you run it again, it may be green. This is actually caused by the two lines of code in my Log method (non-thread safe method) being called by multiple threads:

1 Console.ForegroundColor = color;2 Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");

We can make some small changes to make the Log method thread-safe (there are many ways to do it in C#, this is just one of them):

 1 [MethodImpl(MethodImplOptions.Synchronized)] 2 private static void Log(ConsoleColor color, string message, bool newLine = false) 3 { 4     if (newLine) 5     { 6         Console.WriteLine(); 7     } 8     Console.ForegroundColor = color; 9     Console.WriteLine($"{message,-20} : {Thread.CurrentThread.ManagedThreadId}");10 }

It seems a little off topic, back to the topic, supporting the await keyword in the catch and finally statement blocks does not require the support of the IL instruction, nor the support of the CLR, but is just the code conversion made by the compiler (await/async is like Same as lambda to delegate). I won’t expand the specific IL, it’s too huge. Here’s a picture to see the general situation:

The code we wrote in CallerMethod was transferred to Move

Next

(For more detailed information, please visit a blog of garden friend "Dev_Eric": Advanced article: Using IL as a sword, pointing directly to async/await) (including the await statements in catch and finally ). 2. Exception

Filter

In fact, this language feature has been supported in VB and F# for a long time, and now it can also be used in C#6.

1 try { … }2 catch (Exception e) when (filter(e))3 {4     …5 }

The when section is where the exception filter takes effect. When is followed by an expression

. If the expression result is true, enter The current catch statement block. 3. Reference

Asynchronous Programming Patterns

C# 6.0 await in catch/finally

C# 6.0 Exception filters

http:/ /www.php.cn/

The above is the detailed content of C# exception enhancement. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software