In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "what are the ways in which C# handles exceptions". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the ways in which C# handles exceptions?"
With regard to exceptions, they have been with us since we started writing code, but we haven't started yet, and we don't have consciousness in our minds.
Exception: an error occurred while the program was running
Exception object: encapsulates all kinds of errors in the program into objects
I once remember that in the first interview, the interviewer asked me such a turning question, "how do you usually solve all kinds of problems?" a: at that time, I was surprised and looked at other people's facial classics and mentioned this problem. I didn't think much about "first of all, find out where the mistake went wrong, locate the wrong position, and see what's wrong." Q: then tell me what the anomalies are, the causes of the exceptions, and how to deal with them. A: null pointer, out of index exception, en en. It was awkward at that time, but when I asked about the anomaly, my answer was so simple and lack of thinking.
In practical work, catching exceptions and collecting and analyzing them are very important to solve the problem.
Exception class analysis
The SystemException class inherits Exception, which is the base class for all other exception classes in the System namespace, and when I catch an exception, the first thing I look at is the Exception object information. The key members of Exception are as follows
Write the picture description here.
1.Message attribute: error message that causes the exception
[_ DynamicallyInvokable] public virtual string Message {[_ DynamicallyInvokable] get {if (this._message! = null) {return this._message;} if (this._className = = null) {this._className = this.GetClassName ();} return Environment.GetRuntimeResourceString ("Exception_WasThrown", new object [] {this._className});}}
The Message property is read-only, and GetRuntimeResourceString is the string that gets the runtime resource. The returned string is an error message or an empty string that caused the exception.
2.Data: a collection of key / value pairs for other exception information of
Public virtual IDictionary Data {get {if (_ data = = null) if (IsImmutableAgileException (this)) _ data = new EmptyReadOnlyDictionaryInternal (); else _ data = new ListDictionaryInternal (); return _ data;}}
3.StackTrace: the name and signature of the method called before the exception occurs
Public static string StackTrace {[SecuritySafeCritical] get {new EnvironmentPermission (PermissionState.Unrestricted) .Demand (); return GetStackTrace (null, true);}}
4.Source property: contains the name of the application or object that generated the exception
5.TargetSite property: the method that throws the current exception
6.GetBaseException method: returns System.Exception, which is the "base" class for all exception classes.
Common exception classes
There are many exception types, all of which are inherited from SystemException. These exception types can be divided into the following categories: 1. Related to array sets 2. Related to member visits 3. Related to the parameters 4. Related to arithmetic related 5.IO 6. Of course, there are other anomalies.
1. Related to array collections
IndexOutOfRangeException class: exceptions thrown when the index is out of range
ArrayTypeMismatchException class: array collections store exceptions thrown by incorrect data types
RankException class: handling exceptions thrown by dimensional errors
2.IO-related exceptions
IO-related exceptions are inherited from the IOException class, which is used to handle exceptions thrown during file input and output operations. The five direct derived classes of the IOException class are as follows.
DirectoryNotFoundException class: the exception that is thrown when the specified directory is not found.
FileNotFoundException class: the exception that is thrown when the file is not found.
The EndOfStreamException class: handles exceptions that have reached the end of the stream and continue to read the data.
FileLoadException class: the exception that is thrown when the file cannot be loaded.
PathTooLongException class: an exception that is thrown because the file name is too long.
3. Members access related exceptions
Exceptions related to member access inherit from the class MemberAccessException, which inherits from SystemException.
FileAccessException: exception thrown when a failure to access a field member
MethodAccessException: an exception is thrown when a failure to access a method member
MissingMemberException: there is no exception thrown by the member
4. Parameter-related exception
Exception classes ArgumentException related to parameters are inherited from SystemException, and an exception occurs when handling passing parameters to method members
ArgumentOutOfRangeException: an exception that is thrown when a parameter is not within a given range
ArgumentNullException: exception thrown if the parameter is null (null is not allowed)
5. Related to arithmetic
The ArithmeticException exception class is used to handle arithmetic-related exceptions, and its related subclasses are as follows
DivideByZeroException: an exception thrown by an integer decimal attempt to divide by 0 (the divisor cannot be 0)
NotFiniteNumberException: an exception thrown by an infinite or non-negative value in a floating-point operation
6. Other anomalies
NullReferenceException: when an object is not instantiated and references the exception that is thrown
InvalidOperationException: throws an exception when the current state of the calling object to the method is invalid
InvalidCastException: handles exceptions thrown during type conversion
OutOfMemoryException: handling exceptions caused by insufficient memory
StackOverflowException: handling errors caused by stack overflow
Exception capture
The provision of try and catch blocks in C # provides a structured exception handling scheme, all possible exceptions must be handled properly, try catch itself will not affect the performance of the system, and try catch will not affect the performance of the system when no exception occurs. When it is affected, it is when an exception occurs.
Keyword try catch finally. Execute the statements in try first, and if an exception is thrown, it will be caught by catch. The statements in finally are executed regardless of whether an exception occurs. Another uncommonly used throw keyword: when a problem occurs, the program throws an exception.
Class Program {static void Main (string [] args) {DivideNumber div = new DivideNumber (); div.DivideMethod (2,0); Console.ReadKey ();}} class DivideNumber {int result; public DivideNumber () {result = 0 } public void DivideMethod (int a result int b) {try {result = a / b;} catch (DivideByZeroException e) {Console.WriteLine ("exception, the divisor cannot be 0meme.message:" + e.Message) } finally {Console.WriteLine (the result of $"{a} divided by {b} is" + result);}} exception handling principles and recommendations
In the actual development, how to write the exception depends on the stability and fault tolerance of the system.
To catch a specific exception
When catching exceptions, we often write catch (Exception ex). This is not a specific exception, but it is best to be specific to exception classes such as ArgumentException, FormatException, and so on. Do not throw "new Exception ()".
Nothing is done in catch, and exceptions are thrown to the top level.
This situation may be quite common when writing your own demo. Do nothing under the code catch (Exception ex). Don't do it. Remember that exceptions should be thrown at the top level
Rational use of finally blocks
The finally keyword is executed no matter what type of exception is thrown, and most of the time code that can be executed under a finally block can also be written in catch. So when is it appropriate to use the finally keyword, such as cleaning resources, closing streams, restoring status, and so on?
The exception thrown should be recorded.
Of course, not all the exceptions in the program have to be recorded, and some exceptions are recorded to facilitate the analysis of specific problems. Some log libraries log4net, EIF.
Do not only record the value of Exception.Message, but also record Exception.ToString ()
In the previous example, the e.Message I printed just output "try to divide by 0". The error message is not specific and is not recommended. The Tostring method contains stacktrace, internal exception information, Message... Usually this information is more important than a single Message.
Do not use "throw exception" as a result of function execution
"throw an exception" should be thrown to the top level, but not as a result of method execution, and the result of a method cannot be an exception class.
Each thread should contain a try/catch block
When a child thread is created to execute a task, the main thread does not know the exception of the child thread, so each thread needs a try, catch.
Comments from the Code thinker
When I was a project manager for a C# project, I also thought about how to effectively practice exception handling in the project team.
First of all, exception handling should be part of the system design specification that appears in the system design document, not just a technical implementation.
As part of the design document, exception handling should focus on system fault tolerance and stability (as the landlord mentioned). Then, according to this specification, we will discuss and select the various technical details used in exception handling.
For example, when designing a service, there must be exception handling at the service's invocation interface, otherwise any harmful data sent from the client may cause the server to hang up.
For example, the handling of exceptions must be clearly stated in the design of the system, and exceptions cannot be handled in any module.
At this point, I believe you have a deeper understanding of "what is the way C# handles exceptions?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.