Reading notes-CLR via C # exception and state management

Source: Internet
Author: User
Tags finally block stack trace

Objective

This book in the past few years fragmented read two or three times, as a classic book, should repeat read and reread, since I began to write Bo, I am also ready to think of the classic good book reread carefully read it again, and put the notes into the blog, good memory than bad writing, but also in the process can deepen their understanding of the depth, And, of course, sharing it with friends from the technology community.

Tips
  • vs Debug Catch block, Watch Window variable: $exception View the currently thrown exception object
  • Exception catch is top-down, backtracking call stack, throws unhandled exception if not found
  • The order of execution of the exception: the body is executed first, then the catch is executed, and finally
  • Order of execution of stack exceptions: Parentbody childbody childcatch childfinally parentcatch parentfinally
  • In. NET 4 and later versions, the first exception capture that occurs in the AppDomain is registered with the AppDomain's firstchanceexception, which occurs before any catch blocks are searched by the CLR
  • The code in the finally is guaranteed to be executed, regardless of whether the exception occurred (using the WIN32 function TerminateThread to kill the thread, or kill the process with the FailFast method of the WINB32 function terminateprocess or system.environment, and the finally block will not execute. Of course, after the process terminates, Windows cleans up all resources used by the process)
  • If an exception is thrown in a catch or finally, the original exception is lost, and the new exception continues up backwards
  • The CLR can only catch exceptions that are CLS-compliant (from exception-derived exceptions that are considered CLS-compliant), and if C # calls a method of another programming language that throws a non-CLS-compliant exception, then C # code cannot catch the exception, which has some security implications
  • When an exception that is not CLS-compliant is thrown, the CLR automatically constructs an instance of the RuntimeWrappedException class and initializes the private field of the instance to refer to the object that was actually thrown. This allows the CLR to turn non-CLS-compliant exceptions into CLS-compliant exceptions. So any code that captures exception types can capture non-CLS-compliant exceptions, eliminating security breaches
  • After c#2.0, catch captures any exception that is CLS-compliant and incompatible (Exception), and if the direct catch{}, the version of C # can catch CLS-compliant and incompatible exceptions
  • If you want to be compatible with the old CLR behavior [Assembly:runtimecompatibility (Wrapnonexceptionthrows=false)]
  • When an exception is thrown, the CLR internally records the position of the throw instruction (the thrown position), and when a catch catches an exception, the CLR logs the exception's snapping position
  • The StackTrace property of the thrown exception object is accessed within the catch block, and the code responsible for implementing the property invokes the CLR internal code, creating a string that indicates all methods of the exception snap position from the exception throw location
  • Overriding the throw E in a catch resets the starting point of the exception (resets the start of the stack), does not conform to the encoding specification, and is OK if only the throw is used
  • If the code method is inline, it may cause the exception stack trace to not accurately correspond to the source code, and if you want to prevent JIT optimizations from inline, use the compiler switch/debug or [System.Runtime.CompilerServices.MethodImplAttribute (methodimploptions.noinling)]
  • The exception itself string message can contain detailed technical details for tracking debugging, but these messages should not be captured directly by the application layer and should not be displayed to the end user
  • The exception messages for the FCL use localized strings, which developers can consider based on the actual situation
  • When designing and handling exceptions, it is often necessary to sacrifice reliability in exchange for development efficiency
  • Try to avoid capturing System.Exception and then allow the application to continue to allow, a big problem is that the state may be compromised
  • Lock, using, and foreach statements, both use try/finally blocks, and when overriding the destructor, the compiler automatically generates try/finally
  • Exceptions in the Async programming model are "swallowed" and then re-thrown.
  • Coding recommendations, usually after catching and handling exceptions, do not swallow it, use throw alone, throw the same exception
  • About the practice of exception, you can think about it, such as defining application layer exceptions, business layer exceptions, service exceptions, communication anomalies, and then the exception of the FCL "swallowed" log
  • A dynamic object calls a method that throws a TargetInvocationException exception if it fails. The exception that was originally thrown is passed up normally in the call stack. This is a good reason to use C # 's dynamic primitive type instead of reflection. (If you use reflection to invoke a method, the exception within the method cannot be caught properly)
  • Uncaught unhandled exceptions are written to the Windows log
  • In distributed programs, as little as possible to expose the exception information, if the stack information is exposed, the information in the server may be compromised
  • When debugging an exception, focus on the VS menu "debug"-"Exception", which can force some exceptions to occur and prevent them from being "swallowed" (even if it is catch)
  • In addition, the performance impact of exception handling, can avoid, for example, if there is a try prefix method, try to use the method prefix (but the try method can still throw exceptions, such as the style parameter is invalid, will throw ArgumentException, It is also possible to throw outmemoryexception exceptions)
  • A CER is useful if you want to maintain state when unexpected exceptions are thrown. This exception is also called an asynchronous exception. When the CLR loads an assembly, a type object is created in the AppDomain's load heap, the static constructor of the type is called, and the Il Code is JIT-compiled with the cost code. If the operation fails, the CLR throws an exception report failure. (Many implicit non-conformance exceptions, resulting in unpredictable)
  • CER, prepareconstrainedregions a very special method, the JIT compiler calls this method before discovering a try block, and compiles the code in the catch and finally blocks associated with the try in advance. The JIT compiler loads any assembly, creates any type of object, invokes any static constructor, and JIT compiles any method. If any of these operations cause an exception, the exception occurs before the thread enters the try block. When the JIT compiler prepares the method in advance, it also iterates through the call graph, assuming that the method uses [Reliabilitycontractattribute] and pass Consistency.willnotcorruptstate or Consistency.maycorruptinstance enumeration members. This is because the join method can damage the AppDomain or process state, and the CLR will not be able to guarantee State consistency
  • You can call Runtimehelper's PrepareMethod manual preparation method
  • CER article reference: http://www.cnblogs.com/Ninputer/archive/2006/06/30/439757.html
Uncaught exception Handling
    • Winform, onthreadexception virtual method and ThreadException event of application
    • WPF Program Application dispatcherunhandledexceptions and System.WIndows.Therading.Dispatcher unhandledexception and unhandledexceptionf Ilter Events
    • The Unhandledexceptoin event for Silverlight,system.window.application
    • Asp. NET program, System.Web.HttpApplication Error Event
    • For the Errorhandlers property of Wcf,system.servicemodel.dispatcher.chnneldispatche
Contract-type programming

I have time to tidy up this aspect of things, after all, a programming habit of training, need to slowly accumulate to gradually use the new thinking

Reference article:

Http://www.infoq.com/cn/news/2009/02/Code-Contracts-.NET

Http://www.cnblogs.com/lucifer1982/archive/2009/03/21/1418642.html

Reading notes-CLR via C # exception and state management

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.