16. Error handling
To write a function that can fail, and to handle its failure: with a fallback value, with a block that knows the reason for the error, or by passing it on to the caller.
Explanation
Section titled “Explanation”- A function that can fail writes
!before its return type:!عدد64. When it fails, it returnsخطأ.اسم(error.name). - You define the names of your errors in an
اخطاء:(errors) block at the top of the file. ن = ف() والا 0: if it fails, the value is 0. Andوالا خ:followed by a block: inside it,خis the error’s name, and the last line of the block is the fallback value.جرّب ف()(try) inside a!نوعfunction: ifفfails, your function exits with the same error.- Forgetting to handle it is a compile error: your program never reaches run time with a failure you have not decided what to do with.
اخطاء: قسمة_على_صفر
داله اقسم(ا عدد64, ب عدد64) !عدد64: اذا ب == 0: ارجع خطأ.قسمة_على_صفر ارجع ا / ب
اطبع(اقسم(10, 2) والا -1)اطبع(اقسم(10, 0) والا -1)ن = اقسم(7, 0) والا خ: اطبع("فشل: ", خ) 0اطبع(ن)جرّب passes the first failure to whoever called the function:
داله مجموع_نصين(ا نص, ب نص) !عدد64: س = جرّب حلل(ا, عدد64) ص = جرّب حلل(ب, عدد64) ارجع س + ص
اطبع(مجموع_نصين("4", "5") والا -1)اطبع(مجموع_نصين("4", "خمسة") والا -1)An error has context (since 0.11.0): the library’s errors carry what happened, so اطبع(خ) prints for example «صيغة_خاطئة: «ثلاثون» ليس عدداً» (wrong format: «ثلاثون» is not a number), or the path and the system error number for a file error; ارجع خطأ.اسم مع قيم attaches a message to your error, and بسبب خ (because of) the error that came before it. A signature may list its errors: !{غير_موجود, ممنوع} نص. Details in error handling. Runtime errors, such as division by zero or an index outside the list, are not of this kind: they cannot be handled, and they end the program with code 3. Details in dealing with errors.
Exercise
Section titled “Exercise”A function اقرأ_عمر(ن نص) !عدد64 converts the string to a number with جرّب, and returns your error عمر_غير_معقول (unreasonable age) if the age is below 0 or above 150. Try it on «30», «ثلاثون» and «200», and for each case print the reason for the failure with حالات.
Show the solution
اخطاء: عمر_غير_معقول
داله اقرأ_عمر(ن نص) !عدد64: ع = جرّب حلل(ن, عدد64) اذا ع < 0 او ع > 150: ارجع خطأ.عمر_غير_معقول ارجع ع
لكل ن في ["30", "ثلاثون", "200"]: ع = اقرأ_عمر(ن) والا خ: حالات خ: حاله خطأ.عمر_غير_معقول: اطبع(ن, ": عمر غير معقول") حاله _: اطبع(ن, ": ليس عدداً (", خ, ")") تجاوز اطبع(ن, ": العمر ", ع)Common mistakes
Section titled “Common mistakes”Using the result of !عدد64 as if it were عدد64, without جرّب or والا:
داله نصف(ن نص) !عدد64: ارجع جرّب حلل(ن, عدد64) / 2
اطبع(نصف("8"))Exit code: 2
In the error catalog: E0399
The fix: اطبع(نصف("8") والا 0), or جرّب inside a function that returns !نوع.
See also
Section titled “See also”Error handling in the reference · Dealing with errors