الاستثناءات: حاول... وأخيراً تعبير (F#)
try...finallyيمكنك التعبير إلى تنفيذ تنظيف-فأعلى تعليمات برمجية حتى لو يطرح حظر من تعليمات برمجية استثناء.
try
expression1
finally
expression2
ملاحظات
try...finallyيمكن استخدام التعبير بتنفيذ تعليمات برمجية في expression2في بناء الجملة السابقة بغض النظر عن ما إذا كان باستثناء هو التي تم إنشاؤها أثناء التنفيذ expression1.
النوع expression2ولا تساهم القيمة للتعبير بأكمله؛ النوع إرجاع متى إستثناء لا تحدث القيمة الأخيرة في expression1. When an استثناء does occur, لا القيمة هو returned و the تدفق of عنصر تحكم transfers إلى the التالي matching استثناء handler لأعلى the يتصل مكدس. If لا استثناء handler هو found, the برنامج terminates. قبل the تعليمات برمجية في a matching handler هو executed أو the برنامج terminates, the تعليمات برمجية في the finally فرع هو executed.
The following تعليمات برمجية demonstrates the استخدم of the try...finally تعبير.
let divide x y =
let stream : System.IO.FileStream = System.IO.File.Create("test.txt")
let writer : System.IO.StreamWriter = new System.IO.StreamWriter(stream)
try
writer.WriteLine("test1");
Some( x / y )
finally
writer.Flush()
printfn "Closing stream"
stream.Close()
let result =
try
divide 100 0
with
| :? System.DivideByZeroException -> printfn "Exception handled."; None
The إخراج إلى the console هو كـ follows.
Closing stream
Exception handled.
كـ you can see من the إخراج, the stream was مغلق قبل the outer استثناء was handled, و the ملف test.txt يحتوي على the نص test1, which indicates that the buffers were flushed و written إلى قرص even though the استثناء transferred عنصر تحكم إلى the outer استثناء handler.
ملاحظة that the try...with construct هو a separate construct من the try...finally construct. Therefore, if your تعليمات برمجية يتطلب كلاهما a with حظر و a finally حظر, you have إلى nest the الثاني constructs, كـ في the following تعليمات برمجية مثال.
exception InnerError of string
exception OuterError of string
let function1 x y =
try
try
if x = y then raise (InnerError("inner"))
else raise (OuterError("outer"))
with
| InnerError(str) -> printfn "Error1 %s" str
finally
printfn "Always print this."
let function2 x y =
try
function1 x y
with
| OuterError(str) -> printfn "Error2 %s" str
function2 100 100
function2 100 10
في the سياق of computation expressions, including تسلسل expressions و غير متزامن workflows, try...finally expressions can have a مخصص implementation. لمزيد من المعلومات، راجع التعبيرات احتساب (F#).
راجع أيضًا:
المرجع
الاستثناءات: حاول... مع تعبير (F#)