Learn to use exceptions
In C #, run-time errors in a program are propagated in a program by using a mechanism called "exceptions." The exception is thrown by the wrong code and is captured by code that corrects the error. Exceptions can be thrown by the common language runtime (CLR) of. NET or by code in a program. Once an exception is thrown, the exception propagates up the call stack until it finds a statement against it catch
. uncaught exceptions are handled by a system-supplied generic exception handler, which is a dialog box that you often see.
An exception is represented by a class that derives from Exception. This class identifies the type of exception and contains properties that describe the exception in detail. Here is a demonstration of customizing a new Exception class, and optionally a property that you can customize to configure the exception, and then use throw
the keyword to raise the object (that is, the exception).
1 /// <summary>2 ///defining a new Exception3 /// </summary>4 classmyexception:exception5 {6 PublicMyException (stringmsg) { }7 }8 9 /// <summary>Ten ///throws a newly defined exception One /// </summary> A Static voidthrowmyexcetion () - { - Throw NewMyException ("Sorry, this is test!"); the}
After an exception is thrown, the runtime checks the current statement to determine whether it is in a try
block. If it is, check try
any blocks associated with the block catch
to determine whether they can catch the exception. Catch
a block typically specifies an exception type catch
, and if the block is of the same type (or match) as the base class of the exception or exception, the block is capable of catch
processing.
1 Static voidMain (string[] args)2 {3 Try4 {5Throwmyexcetion ();//calling the method that throws the exception directly6 }7 Catch(myexception e)8 {9 Console.WriteLine (e);Ten } One A Console.read (); -}
If the statement that throws the exception is not try
in the block, or if the block containing the statement try
does not have a matching catch
block, the runtime checks to see if there are try
statements and blocks in the calling method catch
. The runtime continues to search for compatible blocks in the call stack catch
. After the block is found and executed catch
, control is passed to catch
the next statement after the block.
A try
statement may contain more than one catch
block. The first statement that can handle the exception is executed catch
, and any subsequent catch
statements are ignored, even if they are compatible. Therefore, in any case, you should arrange the catch block in the order from most specific (or most derived) to least specific. For example:
1 Static voidMain (string[] args)2 {3StreamWriter SW =NULL;4 5 Try6 {7SW =NewStreamWriter (@"C:\book\ The story of Xiao ER and small three. txt");8Sw. Write ("You are .");9 }Ten Catch(FileNotFoundException e) One { A //put the specific exception in the first place - Console.WriteLine (e); - } the Catch(IOException e) - { - //will not be specifically placed in the relative back of the position - Console.WriteLine (e); + } - Catch(Exception e) + { A Console.WriteLine (e); at } - finally - { - if(SW! =NULL) - { - SW. Close (); in } - } to + Console.read (); -}
catch
the runtime checks the block before executing the block finally
. Finally
blocks enable programmers to purge try
any ambiguous state that might have been left behind by the aborted block, or to release any external resources (such as case handles, database connections, or file streams) without having to wait for the garbage collector in the runtime to terminate the objects. For example:
1 Static voidMain (string[] args)2 {3FileStream fs =NULL;4FileInfo fi =NewFileInfo (@"The story of Xiao ER and small three. txt");5 6 Try7 {8FS =fi. OpenWrite ();9Fs. WriteByte (0);Ten } One finally A { - //Remember, if you forget close, an IO exception will be thrown! - //if (fs! = NULL) the //{ - //FS. Close (); - //} - } + - Try + { AFS =fi. OpenWrite (); atFs. WriteByte (1); -Console.WriteLine ("ok!"); - } - Catch(IOException e) - { -Console.WriteLine ("fail!"); in } - to Console.read (); +}
"Fail!", this is because the comments on the need to close the file stream statement, you can try to remove the comments to see the results, remember Oh, IO operation should be at the end of the release of resources.
If WriteByte()
an exception is thrown, the .Close()
try
code in the second block that tries to reopen the file fails without calling FS, and the file remains locked. Because the block finally
is being executed, even if an exception has been thrown, the blocks in the previous example finally
allow the file to be closed correctly, helping to avoid errors.
If a compatible block is not found on the call stack after an exception is thrown catch
, one of three cases occurs:
If the exception appears in a destructor, abort the destructor and call the base destructor, if any.
If the call stack contains a static constructor or a static field initializer, a typeinitializationexception is thrown and the original exception is assigned to the InnerException property of the new exception.
Terminates the thread if it reaches the beginning of the thread.
"Bo Master" anti-bone Aberdeen
"Provenance" http://www.cnblogs.com/liqingwen/p/6193534.html
"Reference" Official Microsoft documentation
[C #] Learn to use exceptions (in a collation)