كلمة المفتاح except في Python
مثال
إذا أحدث جملة الخطأ خطأً فيجب طباعة "حدث خطأ ما":
try: x > 3 except: print("حدث خطأ ما")
التعريف والاستخدام
استخدمت كلمة المفتاح except في مكتبة try ... except. إنها تعرف الكود الذي يجب تشغيله عند إطلاق خطأ في مكتبة try.
يمكنك تعريف قطع مختلفة للخطأ المختلفة، وكذلك قطع تنفيذها عند عدم وجود مشكلة، يرجى الرجوع إلى المثال أدناه.
More Examples
Example 1
If NameError is raised, write a message, and if TypeError is raised, write another message:
x = "hello" try: x > 3 except NameError: print("You have a variable that is not defined.") except TypeError: print("You are comparing values of different types")
Example 2
Try to execute a statement that raises an error, but do not define an error type (in this case, ZeroDivisionError):
try: x = 1/0 except NameError: print("You have a variable that is not defined.") except TypeError: print("You are comparing values of different types") except: print("Something else went wrong")
Example 3
If no error occurs, write a message:
x = 1 try: x > 10 except NameError: print("You have a variable that is not defined.") except TypeError: print("You are comparing values of different types") else: print("The 'Try' code was executed without raising any errors!")