Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet53/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   49   50   51   52   53   54   55   56   ...   78
Bog'liq
C sharp

 Finally Block
As the last clause in the try-catch statement, a finally block can be 
added. This block is used to clean up certain resources allocated in the try 
block. Typically, limited system resources and graphical components need 
to be released in this way once they are no longer needed. The code in the 
finally block will always execute, whether or not there is an exception. 
This will be the case even if the try block ends with a jump statement, 
such as return.
In the example used previously, the file opened in the try block should 
be closed if it was successfully opened. This is done properly in the next 
code segment. To be able to access the StreamReader object from the 
Chapter 21 exCeption handling


125
finally clause, it must be declared outside of the try block. Keep in mind 
that if you forget to close the stream, the garbage collector will eventually 
close it for you, but it is good practice to do it yourself.
StreamReader sr = null;
try {
sr = new StreamReader("missing.txt");
}
catch (FileNotFoundException) {}
finally {
if (sr != null) sr.Close();
}
The previous statement is known as a try-catch-finally statement. 
The catch block may also be left out to create a try-finally statement. 
This statement will not catch any exceptions. Instead, it will ensure the 
proper disposal of any resources allocated in the try block. This can 
be useful if the allocated resource does not throw any exceptions. For 
instance, such a class would be Bitmap in the System.Drawing namespace.
using System.Drawing;
// ...
Bitmap b = null;
try {
b = new Bitmap(100, 50);
System.Console.WriteLine(b.Width); // "100"
}
finally {
if (b != null) b.Dispose();
}
Chapter 21 exCeption handling


126
Note that when using a Console Project a reference to the System.
Drawing assembly needs to be manually added for those members to 
be accessible. To do so, right-click the References folder in the Solution 
Explorer window and select Add Reference. Then from Assemblies ➤ 
Framework, select the System.Drawing assembly and click OK to add its 
reference to your project.

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   49   50   51   52   53   54   55   56   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling