About C # exception handling

About abnormal, from the time we started writing the code begins with us, but that time has not started, mind and consciousness that is no exception.
Exception: An error occurred during program run,
the exception object: an object packaged as a variety of errors occurred program will
recall the first interview, when the interviewer asked me such a question of turning "you usually are how to address each emerging kinds of problems ", a: heart was surprised to see someone else's face was also mentioned this issue, did not think," first of all they look for what went wrong out, locate the error position, to see there was anything unusual . " q: Then tell me what the cause of abnormal ,, an exception, how to handle. a: null pointer, the index exceeded abnormal, en en ......... was quite embarrassing, but I asked the abnormal answer so simple, lack of thinking.
In the actual work, catch the exception, collection and analysis of abnormal vital to solve the problem.

Exception class analysis of
common exception class
exception is caught
exception handling principles and recommendations
SystemException Exception class inheritance, the former is the System namespace base class for all other exception classes, catch exceptions when the first thing I look at is the Exception object information. Exception important member as shown
here Write Image Caption
1.Message properties: Error messages generated reason for 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 });
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Message property is read-only attribute, GetRuntimeResourceString is to obtain run-time resource strings. An error message is returned string causes an exception or an empty string.
2.Data: key information about the exception / value pairs

Virtual the IDictionary the Data {public
GET {
IF (the _data == null)
IF (IsImmutableAgileException (the this)) = the _data new new EmptyReadOnlyDictionaryInternal ();
the else
the _data new new ListDictionaryInternal = ();
return the _data;
}
}
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
3.StackTrace: abnormal appearance before calling the method name and signature

the StackTrace static String public
{
[SecuritySafeCritical]
GET
{
new new EnvironmentPermission (PermissionState.Unrestricted) .Demand ();
return getStackTrace (null, to true);
}
}
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
4.Source properties: containing generates an exception or the name of the application object
5.TargetSite properties: this method throws an exception
6.GetBaseException method: returns System.Exception, it is a "base" class for all exception classes.

Common exception class

There are many types of exceptions, they are inherited from SystemException, these anomalies roughly divided into the following types of these types of arrays 1 and 2 with the members of a set of related parameters related to access information about 3. 4. related mathematically related 5.IO 6. of course, there are other anomalies.
1. For the array collection
IndexOutOfRangeException categories: index out of the range of initiators of abnormal
ArrayTypeMismatchException categories: storing a set of data array abnormality caused by an incorrect type
RankException categories: processing dimension error caused exception
2.IO abnormalities associated
with the IO-related exceptions IOException inherited from class, the processing for abnormality when a file input-output operation caused, directly IOException class five derived classes as follows.
DirectoryNotFoundException class: not specified directory find and thrown.
FileNotFoundException class: file not found exception that is thrown.
EndOfStreamException categories: process has reached the end of the stream will continue to read data thrown.
FileLoadException categories: Could not load file and thrown.
PathTooLongException categories: file name too long thrown.
3. Members access information about anomalies
and abnormalities associated with member access MemberAccessException inherit from this class that inherits from SystemException.
FileAccessException: Exception Access member field failure caused by
MethodAccessException: access method throws an exception member fails
MissingMemberException: absence of exception thrown member
4. The parameters related to abnormalities
parameter related ArgumentException exception classes inherit from SystemException, exception occurred while processing method to pass parameters members
ArgumentOutOfRangeException: exception when a parameter is not within a given range caused
ArgumentNullException: the case where the parameter is null (not allow null) initiated exception
5 ... associated with the arithmetic
processing related to the exception class ArithmeticException arithmetic exception for its associated subclasses as follows
DivideByZeroException: an integer of 0 decimal attempts to divide exception thrown (dividend is not 0)
NotFiniteNumberException: negative infinity, or floating-point operations thrown exception occurred
6. other abnormal
NullReferenceException: when an object is instantiated and no reference exception thrown
InvalidOperationException: initiated when an object method calls the current status is invalid abnormal
InvalidCastException: type conversion caused during handling exceptions
OutOfMemoryException: insufficient memory processing exception that is thrown
StackOverflowException: processing stack overflow lead mistake

Abnormal capture
c # try and catch block to provide exception handling provides a structured program, all possible exceptions must be handled properly, try catch itself does not affect system performance, try an exception occurs in the absence of catch will not affect system performance. Affected is the time when the exception occurred.
Keyword try catch finally. Try to execute the statements inside, if an exception is thrown catch will be captured. Whether abnormal finally will be executed inside the statement does not appear. Also do not throw common keywords: 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,int b)
{
try
{
result = a / b;
}
catch (DivideByZeroException e)
{
Console.WriteLine("exception,被除数不能为0,e.message:" + e.Message);
}
finally {
Console.WriteLine($"{a}除以{b}的结果是"+result);
}
}
}
1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
13 is
14
15
16
. 17
18 is
. 19
20 is
21 is
22 is
23 is
24
25
26 is
27
28
29
30
31 is
the results of FIG:
write here described image

Exception handling principles and recommendations
in the actual development, abnormalities in the end need to how to write, stability and fault tolerance of the system and still have certain requirements.

To capture specific exceptions
when catching exceptions, we often customary to write catch (Exception ex), this is not a specific exception, it is best to specific ArgumentException, FormatException and other exception classes, do not throw "new Exception ()"
catch in what is not dry, an exception is thrown To top
this situation may be more common at the time to write their own demo, and what is not dry in writing catch (Exception ex) piece of code that do not. To top that appears abnormal remember thrown
rational use of block finally
finally keyword is no matter what type of exception thrown will be executed, the code can perform most of the time in the finally block, which can be written in the catch. So finally keyword in the end under what circumstances it is appropriate, such as cleaning up resources, close the stream, return status.
Exceptions thrown to record the
course of the program appears to be an exception and not all recorded, or recorded some exceptions to facilitate analysis of specific issues. Some logging library log4net, EIF ......
do not just record the value Exception.Message also need to record Exception.ToString ()
just preceding example, e.Message I printed output just "trying to divide by zero" prompt no specific error message, this is not recommended. Tostring method contains the stacktrace, internal anomalies, Message ...... this information is usually more important than just a Message
Do not "thrown" an execution as a result of the function
"thrown" should be thrown to the top, but not as a result of performing a method, the method can not be a result of abnormal category.
Each thread comprises a try / catch block
When you create a child thread to perform the task, the main thread will not know the unusual circumstances of the child threads, each thread requires a try, catch.
Comments from the "code thinker" of
when the project manager C # project before, and I I thought about how to effectively deal with unusual practice in project teams.
First, exception handling should be part of the design of the Statute of the system appear in the system design documentation, not just a technology implementation.
As part of the design documentation, it should focus on the exception handling system fault tolerance and stability (As mentioned landlord). Details of various techniques and according to the statute, and discussed in detail again selected for use in exception handling.
For example, when designing the service, there must be a call to exception handling interface services, or any harmful pass over client data can make server hang.
For example, in the design of exception handling system, must be clearly stated, you can not just handle exceptions in which module.
These are my personal experience, but also look through friends more exchanges
---------------------
Author: zhanglinblog
Source: CSDN
Original: https: // blog. csdn.net/kebi007/article/details/78221083
Disclaimer: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/woxihuadabai/p/11231789.html