פייתון/פייתון גרסה 3/חריגות

מתוך ויקיספר, אוסף הספרים והמדריכים החופשי

פייתון תומכת בטיפול בחריגות כלומר יצרת תוכנית שתבדוק תקינות של קוד או הכנסת ערכים אליו.

במקרה שהתוכנית תתקל בסיטואציה חריגה, לרוב שגיאה או נתונים עבורם תוצאת החישוב הרצויה איננה מוגדרת, היא תציג שגיאה.

החריגה הנזרקת היא אובייקט, שיילכד במעלה הקריאה לפונקציה שזרקה אותו, בבלוק ייעודי מהצורה try ... except, שם יטופל באופן ספציפי. אם חריגה לא נלכדת על ידי המתכנת, היא נלכדת על ידי המפרש.

מבנה[עריכה]

def insert_number():
    
    try:
        <true condition>
    except : #ValueError
        <raise error - the condition is not happing >
    else:
        <if there is no exception >    
    
    finally:
        <will happen no matter to the condition>

דוגמה[עריכה]

def insert_number():
    while True:
        try:
            n = int(input('insert an int: '))
            return n
        except : #ValueError
            print("you didn't insert an int")

print(insert_number())

קיימות חריגות שונות שומרות במערכת כמו "ValueError", "ZeroDivisionError" ועוד במערכת פייתון.

כאשר מייצרים קטע קוד שבודק חריגה נהוג להוסיף בשורת ה-except את סוג החריגה. במקרה שלנו יכולנו לרשום, :except ValueError, בכדי לעדכן את קורא התכנית כי מדובר בחריגה של טיפוס.

הדפסת הודעת השגיאה[עריכה]

החריגות השמורות במערכת של פייתון כוללות הודעות אוטומטיות (כגון ValueError). ניתן להציגן על ידי קריאה:

def insert_number():
    while True:
        try:
            n = int(input('insert an int: '))
            return n
        except ValueError as error:
            print("value error: ", error)

print(insert_number())

>>>insert an int: hello
>>>value error:  invalid literal for int() with base 10: 'hello'

else, finally[עריכה]

def insert_number():
    try:
        x = int(input('insert a number: '))
        y = int(input('insert a number: '))
        result = x / y
    except ZeroDivisionError:
        print ("division by zero!")
    else:
        print ("result is", result)
    finally:
        print ("executing finally clause")

print(insert_number())

>>>insert a number: 2
>>>insert a number: 0
>>>division by zero!
>>>executing finally clause
>>>None

(קבלנו none מפני שהפונקציה אינה מחזירה דבר)

הצגת שגיאה למשתמש[עריכה]

ניתן להציג חריגה למתכנת באמצעות המילה השמורה raise (מתפקדת כ-retrun) ושימוש ב-Exception.

def division(a,b):
    try:
        print (a/b)
    except ZeroDivisionError:
        raise Exception( "You can't divide by zero!")

print(division(2,0))

>>> 
Traceback (most recent call last):
  File "C:/Users/user/Downloads/de/cl.py", line 3, in division
    print (a/b)
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:...", line 7, in <module>
    print(division(2,0))
  File "C:...", line 5, in division
    raise Exception( "You can't divide by zero!")
Exception: You can't divide by zero

בדוגמה הקודמת יכלנו לבצע:

def insert_number():
        if True:
            n = int(input('insert an int: '))
            return n
        else:
            raise ValueError
        
print(insert_number())

>>>insert an int: a
Traceback (most recent call last):
  File "C:...", line 8, in <module>
    print(insert_number())
  File "C:...", line 3, in insert_number
    n = int(input('insert an int: '))
ValueError: invalid literal for int() with base 10: 'a'

raise מתפקד כ-return[עריכה]

def insert_number(n):
    if True:
        raise ValueError
        return n



try:
    print(insert_number(4))

except ValueError:
    print("value is not emptiness")

>>>value is not emptiness

במקרה שלנו בצענו בדיקה שמכניסה מספר אל פונקציה.

בין אם המספר הוא אפס או לא תמיד עולה שגיאה ולכן פקודת ה-try היא תמיד שגויה ועל כן פיתון פונה ל-except

בנית חריגה[עריכה]

ניתן לייצר טיפוס חריגה באמצעות מחלקות.

קישורים חיצוניים[עריכה]