PythonPython · Chapterبەش 10 · Lectureوانە 10.2

Handling Errors with try and exceptمامەڵەکردن لەگەڵ هەڵاوێردە بە try و except

Stop programs from crashing on bad input: catch exceptions with try and except, add else and finally, name the exceptions you expect, write a get_int() function that asks until the input is valid, and raise your own exceptions.

ڕێگری لە کەوتنی بکە بە خراپ: بە try و except بگرە، else و finally زیاد بکە، ناوی چاوەڕوانکراو بهێنە، get_int() بنووسە کە دەپرسێت تا دروست بێت و خۆت دروست بکە.

22 min read22 خولەک خوێندنەوە · 19 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Tell exceptions apart from syntax errors and explain what happens when an exception is not handled.
  • Catch exceptions with try and except, and follow which lines run and which are skipped.
  • Use else and finally, and keep the try block small.
  • Catch specific exceptions (one or several), read their message with as, and avoid a bare except:.
  • Write get_int() and get_int_between() to read numbers safely, and raise your own exceptions with raise.
  • Explain how an exception travels through the call stack, and use assert for your own checks only.
  • لە جیا بکەیتەوە و ڕوونی بکەیتەوە کاتێک چارەسەر ناکرێت چی ڕوو دەدات.
  • بە try و except بگریت و بزانیت کام دێڕ جێبەجێ دەبێت و بازی بەسەر کامدا دەدرێت.
  • else و finally بەکار بهێنیت و بلۆکی try بچووک بهێڵیتەوە.
  • دیاریکراو بگریت (یەک یان چەند دانە)، پەیامەکەیان بە as بخوێنیتەوە و خۆت لە except:ـی ڕووت بپارێزیت.
  • get_int() و get_int_between() بنووسیت بۆ خوێندنەوەی سەلامەتی ژمارە و بە raise خۆت دروست بکەیت.
  • ڕوونی بکەیتەوە چۆن بە دەڕوات و assert تەنها بۆ پشکنینی خۆت بەکار بهێنیت.

When a program crashesکاتێک بەرنامە دەکەوێت

Every program in this course that reads a number uses int(input(...)). It works as long as the user types digits. Type a word instead, and the program stops in the middle:

هەموو ئەم کۆرسە کە ژمارە دەخوێنێتەوە int(input(...)) بەکار دەهێنێت. تا ژمارە بنووسێت کار دەکات. ئەگەر لەبری ئەوە وشەیەک بنووسێت، لە ناوەڕاستدا دەوەستێت:

A tea order that crashesداواکارییەکی چا کە دەکەوێتteas_crash.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
teas = int(input("How many teas? "))
print("That is", teas * 500, "dinars.")

int("two") cannot make a number, so Python raises an exception called ValueError. Nothing in the program deals with it, so Python stops and prints a traceback (Errors and debugging shows how to read one). For the user the program has simply crashed. In this lesson you will learn to handle exceptions: to catch them and react, instead of crashing.

int("two") ناتوانێت ژمارە دروست بکات، بۆیە بە ناوی ValueError دروست دەکات. هیچ شتێک لە مامەڵەی لەگەڵ ناکات، بۆیە دەوەستێت و چاپ دەکات (هەڵەکان و کرمەکوژی پیشانی دەدات چۆن بیخوێنیتەوە). بۆ بە سادەیی کەوتووە. لەم وانەیەدا فێری دەبیت: گرتنیان و وەڵامدانەوەیان، لەبری کەوتن.

Definitionپێناسە

An object that a program raises (throws) when something goes wrong while it runs. It stops normal execution unless the code catches it, with try/except in Python or try/catch in PHP, Java and C#.

ئۆبجێکتێکە کە لە کاتی جێبەجێبووندا دروستی دەکات کاتێک شتێک هەڵە دەچێت. جێبەجێکردنی ئاسایی دەوەستێنێت مەگەر کۆدەکە بیگرێت: بە try/except لە Pythonـدا یان try/catch لە PHP، Java و ⁦C#⁩ـدا.

An injury in a football matchبرینداربوون لە یارییەکی تۆپی پێدا

When a player is hurt, the match does not end. The referee stops play, the medical team runs in and deals with it, and then the match goes on. try is the normal play, the exception is the injury, and except is the medical team that knows what to do.

کاتێک یاریزانێک بریندار دەبێت، یارییەکە کۆتایی نایەت. دادوەر یارییەکە ڕادەگرێت، تیمی پزیشکی دێتە ناو یاریگاکە و چارەسەری دەکات، پاشان یارییەکە بەردەوام دەبێت. try یارییە ئاساییەکەیە، برینداربوونەکەیە و except تیمی پزیشکییە کە دەزانێت چی بکات.

Where the analogy stops workingسنووری ئەم نموونەیە

Play does not restart from the exact moment of the injury: the rest of the try block is skipped. And if no except knows this kind of problem, the match is called off: the program stops.

یارییەکە ڕێک لە ساتی برینداربوونەکەوە دەست پێ ناکاتەوە: پاشماوەی بلۆکی try بازی بەسەردا دەدرێت. ئەگەر هیچ exceptـێک ئەم جۆرە کێشەیە نەناسێت، یارییەکە هەڵدەوەشێتەوە: دەوەستێت.

Quick checkپشکنینی خێراWhich problem can try and except catch?try و except کام کێشە دەگرن؟

Catching an exception: try and exceptگرتنی هەڵاوێردەیەک: try و except

Put the lines that might fail inside try:. Under it, except ValueError: says what to do if a ValueError happens there. Here is the tea order again, run twice:

ئەو دێڕانەی لەوانەیە سەرنەکەون بخەرە ناو try:. لە ژێریدا except ValueError: دەڵێت ئەگەر ValueError لەوێ ڕووی دا چی بکرێت. ئەمە دیسان داواکارییەکەی چایە، دوو جار کاری پێ کراوە:

The same order, with try and exceptهەمان داواکاری، بە try و exceptteas_try.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    teas = int(input("How many teas? "))
    print("That is", teas * 500, "dinars.")
except ValueError:
    print("Please type a whole number, like 3.")
print("Thank you!")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-3

The try block: the risky conversion and the line that uses its result.

بلۆکی try: گۆڕینە مەترسیدارەکە و ئەو دێڕەی ئەنجامەکەی بەکار دەهێنێت.

Lineدێڕی 4-5

The except block runs only if a ValueError happened inside try.

بلۆکی except تەنها کاتێک جێبەجێ دەبێت کە ValueError لەناو tryـدا ڕووی دابێت.

Lineدێڕی 6

After either path, the program carries on normally.

دوای هەر یەک لە دوو ڕێگاکە، بە ئاسایی بەردەوام دەبێت.

How Python runs try and exceptPython چۆن try و except جێبەجێ دەکات
  1. Run tryجێبەجێکردنی try

    Python runs the lines of the try block one by one.

    دێڕەکانی بلۆکی try یەک بە یەک جێبەجێ دەکات.

  2. No problemبێ کێشە

    If no exception happens, the except block is skipped and the program continues after it.

    ئەگەر هیچ ڕوو نەدات، بازی بەسەر بلۆکی exceptـدا دەدرێت و لە دوای ئەوەوە بەردەوام دەبێت.

  3. A problem that is handledکێشەیەک کە چارەسەر دەکرێت

    If a line raises an exception, the rest of try is skipped. Python looks at the except clauses. If one names this kind of exception, its block runs, and then the program continues after the whole statement.

    ئەگەر دێڕێک دروست بکات، پاشماوەی try بازی بەسەردا دەدرێت. سەیری بەشەکانی except دەکات. ئەگەر یەکێکیان ناوی ئەم جۆرە هێنابێت، بلۆکەکەی جێبەجێ دەبێت و پاشان لە دوای هەموو بەردەوام دەبێت.

  4. A problem nobody handlesکێشەیەک کە کەس چارەسەری ناکات

    If no except matches, the exception is not handled and the program stops with a traceback, as before.

    ئەگەر هیچ exceptـێک نەگونجێت، چارەسەر ناکرێت و وەک پێشتر بە دەوەستێت.

Quick checkپشکنینی خێراIn teas_try.py the user types two. Which print() lines run?لە teas_try.pyـدا two دەنووسێت. کام دێڕی print() جێبەجێ دەبن؟

21- گرتنی هه ڵه كان Try - ExceptMR. Ant · Kurdish (Sorani)کوردی (سۆرانی) · 4.4K viewsبینین · 159 likesلایک

A Kurdish (Sorani) lesson on catching errors in Python with try and except, so a wrong input no longer stops the program.

وانەیەکی کوردی (سۆرانی) دەربارەی گرتنی لە بە try و except، بۆ ئەوەی هەڵە چیتر ڕانەگرێت.

Kurdish (Sorani) video, 8:29: catching errors with try and except (MR. Ant Python course, part 21).

ڤیدیۆیەکی کوردی (سۆرانی)، ⁦8:29⁩: گرتنی بە try و except (کۆرسی ⁦MR. Ant⁩، بەشی ⁦21⁩).

Catching an exception: try and exceptگرتنی هەڵاوێردەیەک: try و except

The variable that was never madeئەو گۆڕاوەی هەرگیز دروست نەکرا

Skipping the rest of try has a side effect. If the assignment itself fails, the variable is never created. Code after the try statement that uses it crashes with a new error, a NameError:

بازدان بەسەر پاشماوەی tryـدا کاریگەرییەکی لاوەکیی هەیە. ئەگەر خودی دانانەکە سەرنەکەوێت، هەرگیز دروست ناکرێت. ئەو کۆدەی دوای try بەکاری دەهێنێت بە نوێ دەکەوێت، NameError:

Using teas after a failed tryبەکارهێنانی teas دوای tryـێکی سەرنەکەوتووteas_trap.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    teas = int(input("How many teas? "))
except ValueError:
    print("That is not a whole number.")
print("You ordered", teas, "teas.")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

int("two") fails, so teas = … never happens.

int("two") سەرناکەوێت، بۆیە teas = … هەرگیز ڕوو نادات.

Lineدێڕی 5

This line runs anyway, but teas does not exist.

ئەم دێڕە هەر جێبەجێ دەبێت، بەڵام teas بوونی نییە.

The fix is an else block. It belongs to the same try statement and runs only when no exception happened, so teas surely exists there:

چارەسەرەکە بلۆکی elseـە. سەر بە هەمان tryـە و تەنها کاتێک جێبەجێ دەبێت کە هیچ ڕووی نەدابێت، بۆیە لەوێ teas بێگومان هەیە:

else runs only after successelse تەنها دوای سەرکەوتن جێبەجێ دەبێتteas_else.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    teas = int(input("How many teas? "))
except ValueError:
    print("That is not a whole number.")
else:
    print("You ordered", teas, "teas.")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5-6

The success path lives in else, outside the protected try block.

ڕێگای سەرکەوتن لە elseـدایە، لە دەرەوەی بلۆکی پارێزراوی try.

Quick checkپشکنینی خێراWhen does the else block of a try statement run?بلۆکی elseـی try کەی جێبەجێ دەبێت؟

Catch the exceptions you expectهەڵاوێردەکانی چاوەڕوانکراو بگرە

One try can have several except clauses, one for each problem you expect. Python checks them from top to bottom and runs only the first one that matches. Here a bill is shared between friends at a tea house:

یەک try دەتوانێت چەند بەشێکی exceptـی هەبێت، یەکێک بۆ هەر کێشەیەک کە چاوەڕێی دەکەیت. لە سەرەوە بۆ خوارەوە دەیانپشکنێت و تەنها یەکەمیان کە بگونجێت جێبەجێ دەکات. لێرەدا پسوولەیەک لە چایخانەیەک بەسەر هاوڕێکاندا دابەش دەکرێت:

Sharing a billدابەشکردنی پسوولەshare_bill.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    total = int(input("Total bill (dinars): "))
    people = int(input("Number of people: "))
    share = total / people
except ValueError:
    print("Please type whole numbers only.")
except ZeroDivisionError:
    print("The number of people cannot be zero.")
else:
    print(f"Each person pays {share:.0f} dinars.")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

Dividing by 0 raises ZeroDivisionError.

دابەشکردن بەسەر 0ـدا ZeroDivisionError دروست دەکات.

Lineدێڕی 5-8

Two except clauses, each with its own clear message.

دوو بەشی except، هەر یەکەیان بە پەیامێکی ڕوونی خۆیەوە.

Lineدێڕی 9-10

else: only when both numbers were fine.

else: تەنها کاتێک هەردوو ژمارەکە باش بوون.

Exceptions you will often catch. More runtime errors are listed in Errors and debugging; file errors, the OSError family, in Errors you will meet and Catching file errors. کە زۆرجار دەیانگریت. زیاتر لە هەڵەکان و کرمەکوژیـدا ڕیز کراون؛ ، واتە بنەماڵەی OSError، لە چەند هەڵەیەک کە تووشیان دەبیت و گرتنی هەڵەکانی فایلـدا.
ExceptionTypical causeهۆی باوExampleنموونە
ValueErrorright type, wrong valueجۆری ڕاست، هەڵەint("two")
ZeroDivisionErrordividing by zeroدابەشکردن بەسەر سفردا6000 / 0
KeyErrora dictionary key that does not exist کە نییەprices["milk"]
IndexErrora list position that does not existشوێنێکی کە نییەmarks[5]
TypeErrormixing types that do not fitتێکەڵکردنی جۆرگەلێک کە ناگونجێن"Age: " + 19
FileNotFoundErrora file that does not exist کە بوونی نییەopen("missing.txt")
Quick checkپشکنینی خێراIn share_bill.py, which message does the user see after typing 6000 and 0?لە share_bill.pyـدا، دوای نووسینی 6000 و 0 کام پەیام دەبینێت؟

Try / Except | Python | Tutorial 27Giraffe Academy · Englishئینگلیزی · 71K viewsبینین · 2.2K likesلایک · Partبەشی 4:06–8:43 (ofلە 8:43)

Different kinds of errors, catching the specific one you expect with except ValueError and printing the error message.

جۆرە جیاوازەکانی ، گرتنی ئەو تایبەتەی چاوەڕێی دەکەیت بە except ValueError و پیشاندانی .

Watch 4:06 to the end: different error types, catching each specific error (5:53) and printing the error message (7:15).

لە ⁦4:06⁩ تا کۆتایی سەیر بکە: جۆرە جیاوازەکانی ، گرتنی هەر تایبەت ⁦(5:53)⁩ و پیشاندانی ⁦(7:15)⁩.

Catch the exceptions you expectهەڵاوێردەکانی چاوەڕوانکراو بگرە

One except for several kindsیەک except بۆ چەند جۆرێک

When two different exceptions need the same reaction, list them in a tuple: except (ValueError, IndexError):. Here the user picks one of three marks by its number:

کاتێک دوو جیاواز هەمان وەڵامیان دەوێت، لە ڕیزیان بکە: except (ValueError, IndexError):. لێرەدا یەکێک لە سێ نمرە بە ژمارەکەی هەڵدەبژێرێت:

Two exceptions, one messageدوو هەڵاوێردە، یەک پەیامmany_kinds.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
marks = [78, 91, 64]
try:
    position = int(input("Which mark (1-3)? "))
    print("Mark:", marks[position - 1])
except (ValueError, IndexError):
    print("Please type 1, 2 or 3.")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

marks[position - 1]: typing 5 asks for index 4, which raises IndexError.

marks[position - 1]: نووسینی 5 داوای 4 دەکات کە IndexError دروست دەکات.

Lineدێڕی 5

The tuple catches both ValueError (not a number) and IndexError (no such mark).

هەردووکی ValueError (ژمارە نییە) و IndexError (نمرەی وا نییە) دەگرێت.

To show Python's own message, give the exception a name with as. The name holds the exception object; printing it prints its message:

بۆ پیشاندانی پەیامی خودی ، بە as ناوێک بدە بە . ناوەکە ئۆبجێکتی هەڵدەگرێت؛ چاپکردنی پەیامەکەی چاپ دەکات:

Reading the exception's messageخوێندنەوەی پەیامی هەڵاوێردەas_error.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    number = int(input("A whole number: "))
except ValueError as error:
    print("Problem:", error)
else:
    print("Double:", number * 2)
Quick checkپشکنینی خێراWhich except line catches both ValueError and ZeroDivisionError?کام دێڕی except هەردووکی ValueError و ZeroDivisionError دەگرێت؟

Catch the exceptions you expectهەڵاوێردەکانی چاوەڕوانکراو بگرە

A few more built-in exceptionsچەند هەڵاوێردەیەکی ئامادەی تر

Python has many more built-in exceptions. These are the ones beginners meet next; each name says what went wrong:

زۆر ئامادەی تریشی هەیە. ئەمانە ئەوانەن کە فێرخواز دواتر تووشیان دەبێت؛ ناوی هەر یەکەیان دەڵێت چی هەڵە بوو:

ExceptionRaised whenکەی دروست دەبێتExampleنموونە
ImportErrora module, or a name inside it, cannot be loaded; ModuleNotFoundError is its kind for a missing module، یان ناوێکی ناوی، بار ناکرێت؛ ModuleNotFoundError جۆرەکەیەتی بۆ کە نییەimport maths
EOFErrorinput() reaches the end of the input without reading anything (Ctrl+D on macOS and Linux, Ctrl+Z then Enter on Windows)input() بەبێ خوێندنەوەی هیچ دەگاتە کۆتایی (⁦Ctrl+D⁩ لە macOS و Linux، ⁦Ctrl+Z⁩ پاشان Enter لە Windows)input()
KeyboardInterruptthe user presses the interrupt key, Ctrl+C (Stopping the loop with Ctrl+C) کلیلی ڕاگرتن دادەگرێت، ⁦Ctrl+C⁩ (وەستاندنی خولەکە بە ⁦Ctrl+C⁩)Ctrl+C
OverflowErrora decimal (float) result is too big to store; whole numbers never overflow in Pythonئەنجامێکی زۆر گەورەیە بۆ هەڵگرتن؛ لە هەرگیز تووشی نابنmath.exp(1000)
OSErrora file or folder problem; FileNotFoundError and PermissionError are its kinds (Errors you will meet)کێشەیەکی یان ؛ FileNotFoundError و PermissionError دوو جۆری ئەون (چەند هەڵەیەک کە تووشیان دەبیت)open("missing.txt")
SyntaxErrorthe code breaks Python's grammar (IndentationError is one kind); raised before the program starts (Syntax errors)کۆدەکە یاساکانی زمانی دەشکێنێت (IndentationError جۆرێکیەتی)؛ پێش دەستپێکردنی دروست دەبێت (هەڵەکانی داڕستن)if x == 1
Catching three of themگرتنی سێیانmore_exceptions.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import math

try:
    import maths                      # a misspelt module name
except ImportError as error:
    print(type(error).__name__, "-", error)

try:
    print(math.exp(1000))             # e to the power 1000 is too big
except OverflowError as error:
    print(type(error).__name__, "-", error)

try:
    open("missing.txt")
except OSError as error:
    print(type(error).__name__, "-", error)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

except ImportError also catches ModuleNotFoundError: catching a family catches all its kinds.

except ImportError ModuleNotFoundErrorـیش دەگرێت: گرتنی بنەماڵەیەک هەموو جۆرەکانی دەگرێت.

Lineدێڕی 6

type(error).__name__ is the name of the exception's class.

type(error).__name__ ناوی جۆری .

Quick checkپشکنینی خێراWhich exception does import maths raise?import maths کام دروست دەکات؟

Why not catch everything?بۆچی هەموو شتێک نەگرین؟

A bare except: (with no exception name) catches every exception. That sounds safe, but it hides your own bugs. In this program price is misspelled as prise. The user types a correct number:

except:ـی ڕووت (بەبێ ناوی ) هەموو دەگرێت. وا دەردەکەوێت سەلامەت بێت، بەڵام خۆت دەشارێتەوە. لەم price بە هەڵە prise نووسراوە. ژمارەیەکی دروست دەنووسێت:

A bare except hides a typoexceptـی ڕووت هەڵەیەکی نووسین دەشارێتەوەbare_except.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    teas = int(input("How many teas? "))
    print("Total:", teas * prise)
except:
    print("Please type a whole number.")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

prise does not exist: a NameError.

prise بوونی نییە: NameError.

Lineدێڕی 4-5

The bare except catches the NameError and prints a message that is simply wrong.

exceptـە ڕووتەکە NameError دەگرێت و پەیامێک چاپ دەکات کە بە ڕوونی هەڵەیە.

Name the exception you expect, and Python shows the real bug at once:

ناوی ئەو بهێنە کە چاوەڕێی دەکەیت، ئەوسا یەکسەر ڕاستەقینەکە پیشان دەدات:

except ValueError lets the bug show⁦except ValueError⁩ ڕێگە دەدات باگەکە دەربکەوێتnamed_except.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    teas = int(input("How many teas? "))
    print("Total:", teas * prise)
except ValueError:
    print("Please type a whole number.")

A bare except: also catches KeyboardInterrupt, the exception that Ctrl+C raises when the user wants to stop a program. In a loop that keeps asking, Ctrl+C would then stop working; you will see this with get_int() in Stopping the loop with Ctrl+C.

except:ـی ڕووت KeyboardInterruptـیش دەگرێت، ئەو ⁦Ctrl+C⁩ دروستی دەکات کاتێک دەیەوێت بوەستێنێت. لە کە بەردەوام دەپرسێت، ئیتر ⁦Ctrl+C⁩ کار ناکات؛ ئەمە لەگەڵ get_int()ـدا لە وەستاندنی خولەکە بە ⁦Ctrl+C⁩ دەبینیت.

Quick checkپشکنینی خێراWhy is except ValueError: better than a bare except: around int(input())?بۆچی except ValueError: لە except:ـی ڕووت باشترە لە دەوری int(input())؟

The whole statement: else and finallyهەموو ڕستەکە: else و finally

A try statement can have four parts. You have met three. The fourth, finally, runs in every case: after success, after a handled exception, and even when an exception is not handled (just before the program stops). It is the place for clean-up work such as closing a file or saying goodbye.

try دەتوانێت چوار بەشی هەبێت. سێیانت ناسی. چوارەمیان، finally، لە هەموو حاڵەتێکدا جێبەجێ دەبێت: دوای سەرکەوتن، دوای کە چارەسەر کراوە و تەنانەت کاتێک چارەسەر نەکراوە (پێش ئەوەی بوەستێت). شوێنی کاری پاککردنەوەیە، وەک داخستنی یان ماڵئاوایی.

A flowchart. The try block runs first. Did a line raise an exception? No: the else block runs. Yes: does an except clause match it? Yes: that except block runs. All paths then go through the finally block. After finally the program continues, except on the path where no except matched: there the exception goes on and the program stops with a traceback.هێڵکارییەکی ڕەوت. سەرەتا بلۆکی try جێبەجێ دەبێت. ئایا دێڕێک هەڵاوێردەیەکی دروست کرد؟ نەخێر: بلۆکی else جێبەجێ دەبێت. بەڵێ: ئایا بەشێکی except لەگەڵیدا دەگونجێت؟ بەڵێ: ئەو بلۆکەی except جێبەجێ دەبێت. پاشان هەموو ڕێگاکان بە بلۆکی finallyـدا تێدەپەڕن. دوای finally بەرنامەکە بەردەوام دەبێت، جگە لەو ڕێگایەی هیچ exceptـێک نەگونجا: لەوێ هەڵاوێردەکە بەردەوام دەبێت و بەرنامەکە بە ڕێچکەی هەڵە دەوەستێت.
The four parts of a try statement and the paths through them.چوار بەشەکەی try و ئەو ڕێگایانەی پێیاندا دەڕۆن.CêIT
All four parts at workهەر چوار بەشەکە لە کارداelse_finally.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("  except: cannot divide by zero")
    else:
        print("  else: the result is", result)
    finally:
        print("  finally: this always runs")


print("divide(10, 4)")
divide(10, 4)
print("divide(10, 0)")
divide(10, 0)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

The protected line: dividing by 0 raises ZeroDivisionError.

دێڕە پارێزراوەکە: دابەشکردن بەسەر 0ـدا ZeroDivisionError دروست دەکات.

Lineدێڕی 6-7

else prints the result only after a successful division.

else تەنها دوای دابەشکردنێکی سەرکەوتوو ئەنجامەکە چاپ دەکات.

Lineدێڕی 8-9

finally prints in both calls.

finally لە هەردوو بانگکردنەکەدا چاپ دەکات.

PartبەشRuns whenکەی جێبەجێ دەبێتNeeded?پێویستە؟
try:first, alwaysیەکەم، هەمیشەyesبەڵێ
except X:an exception of type X happened in try جۆری X لە tryـدا ڕووی داat least one except or a finallyلانیکەم یەک except یان یەک finally
else:try finished with no exceptiontry بەبێ تەواو بووoptionalئارەزوومەندانە
finally:in every case, lastلە هەموو حاڵەتێکدا، دوایینoptionalئارەزوومەندانە
Quick checkپشکنینی خێراIn else_finally.py, which lines are printed by divide(10, 0)?لە else_finally.pyـدا، divide(10, 0) کام دێڕانە چاپ دەکات؟

Python Tutorial: Using Try/Except Blocks for Error HandlingCorey Schafer · Englishئینگلیزی · 819K viewsبینین · 16K likesلایک · Partبەشی 4:59–9:18 (ofلە 10:34)

The control flow of a full try statement: printing the exception object, the else block that runs on success, and finally, which always runs.

لە tryـی تەواودا: پیشاندانی ، کە لە کاتی سەرکەوتندا جێبەجێ دەبێت و finally کە هەمیشە جێبەجێ دەبێت.

Watch 4:59–9:18: printing the exception, the else block and the finally clause on a file-opening example.

لە ⁦4:59⁩ تا ⁦9:18⁩ سەیر بکە: پیشاندانی ، و بەشی finally لەسەر نموونەیەکی کردنەوەی .

A safe input function: get_int()کردارێکی نێوخستەی سەلامەت: ⁦get_int()⁩

Catching the error is only half of the job: the user should get another chance. Put the try inside a while True: loop and leave the loop as soon as the input is good. Wrapped in a function, this becomes a tool you can use for every number your programs read:

گرتنی تەنها نیوەی کارەکەیە: دەبێت هەلێکی تر وەربگرێت. try بخەرە ناو while True: و هەر کە باش بوو لە دەربچۆ. کە لە پێچرایەوە، دەبێتە ئامرازێک کە بۆ هەموو ئەو ژمارانەی دەیانخوێننەوە بەکاری بهێنیت:

Ask until the answer is a whole numberبپرسە تا وەڵامەکە ژمارەی تەواو بێتget_int.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def get_int(prompt):
    """Ask again and again until the user types a whole number."""
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please type a whole number.")


teas = get_int("How many teas? ")
price = get_int("Price of one tea: ")
print("Total:", teas * price, "dinars")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

An endless loop: it ends only through return.

: تەنها بە return کۆتایی دێت.

Lineدێڕی 5

If int() succeeds, return hands the number back and leaves the loop and the function at once.

ئەگەر int() سەرکەوێت، return ژمارەکە دەگەڕێنێتەوە و یەکسەر لە و دەردەچێت.

Lineدێڕی 6-7

If not, the message is printed and the loop goes round again.

ئەگەرنا، پەیامەکە چاپ دەکرێت و دیسان دەسووڕێتەوە.

Lineدێڕی 10-12

Now the main program is short and can never crash on a bad number.

ئێستا سەرەکییەکە کورتە و هەرگیز بە ژمارەیەکی خراپ ناکەوێت.

An animation of get_int(). The line return int(input(prompt)) is highlighted and the user types two. A red ValueError appears on that line and an arrow jumps over the rest of the try block straight to except ValueError; the terminal shows Please type a whole number. Another arrow goes back up to while True. The user types 3, the same line turns green, return gives 3 back and teas becomes 3.
An animation of get_int(). The line return int(input(prompt)) is highlighted and the user types two. A red ValueError appears on that line and an arrow jumps over the rest of the try block straight to except ValueError; the terminal shows Please type a whole number. Another arrow goes back up to while True. The user types 3, the same line turns green, return gives 3 back and teas becomes 3.
When int() fails, Python jumps from the failing line to except; the loop then asks again.کاتێک int() سەرناکەوێت، لە دێڕە سەرنەکەوتووەکەوە باز دەداتە except؛ پاشان دیسان دەپرسێت.CêIT

By the way: int() accepts any Unicode decimal digits, so a user who types Kurdish (Eastern Arabic) digits is fine too:

لە پەراوێزدا: int() هەر وەردەگرێت کە بە داینابێت، بۆیە کە ژمارەی کوردی (عەرەبیی ڕۆژهەڵاتی) دەنووسێت کێشەی نییە:

get_int.py from above, typed with Kurdish digits⁦get_int.py⁩ـی سەرەوە، بە ژمارەی کوردی
How many teas? ٣
Price of one tea: ٥٠٠
Total: 1500 dinars
Quick checkپشکنینی خێراInside get_int(), what ends the while True: loop?لەناو get_int()ـدا، چی while True: کۆتایی پێ دەهێنێت؟

A safe input function: get_int()کردارێکی نێوخستەی سەلامەت: ⁦get_int()⁩

Stopping the loop with Ctrl+Cوەستاندنی خولەکە بە ⁦Ctrl+C⁩

get_int() asks until the answer is a whole number. What if the user wants to give up? Pressing Ctrl+C raises KeyboardInterrupt. get_int() catches only ValueError, so KeyboardInterrupt passes through and the program stops, as the user wanted:

get_int() دەپرسێت تا وەڵامەکە بێت. ئەی ئەگەر بیەوێت واز بهێنێت؟ داگرتنی ⁦Ctrl+C⁩ KeyboardInterrupt دروست دەکات. get_int() تەنها ValueError دەگرێت، بۆیە KeyboardInterrupt تێدەپەڕێت و دەوەستێت، وەک دەیویست:

get_int.py: two, then Ctrl+C⁦get_int.py: two⁩، پاشان ⁦Ctrl+C⁩
How many teas? two
Please type a whole number.
How many teas? ^CTraceback (most recent call last):
  File "get_int.py", line 10, in <module>
    teas = get_int("How many teas? ")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "get_int.py", line 5, in get_int
    return int(input(prompt))
               ^^^^^^^^^^^^^
KeyboardInterrupt

Now replace except ValueError: with a bare except:. Ctrl+C is swallowed like a wrong answer and the loop asks again, every time:

ئێستا except ValueError: بە except:ـی ڕووت بگۆڕە. ⁦Ctrl+C⁩ وەک وەڵامێکی هەڵە قووت دەدرێت و هەموو جارێک دیسان دەپرسێتەوە:

A bare except swallows Ctrl+Cexcept:ـی ڕووت ⁦Ctrl+C⁩ قووت دەداتbare_ctrl_c.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except:                       # a bare except: catches Ctrl+C too
            print("Please type a whole number.")


teas = get_int("How many teas? ")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

Catches everything, KeyboardInterrupt included.

هەموو شتێک دەگرێت، KeyboardInterruptـیش.

Quick checkپشکنینی خێراget_int() uses except ValueError:. The user presses Ctrl+C. What happens?get_int() except ValueError: بەکار دەهێنێت. ⁦Ctrl+C⁩ دادەگرێت. چی ڕوو دەدات؟

A safe input function: get_int()کردارێکی نێوخستەی سەلامەت: ⁦get_int()⁩

Checking the range tooپشکنینی سنوورەکانیش

get_int() guarantees a whole number, not a sensible one. A second function adds the range check with a plain if; no exception is needed for that part. This is the same input validation idea as in the while loop lesson, now with both checks:

get_int() مسۆگەر دەکات، نەک ژمارەیەکی گونجاو. دووەم پشکنینی سنوور بە ifـێکی سادە زیاد دەکات؛ بۆ ئەو بەشە پێویست نییە. ئەمە هەمان بیرۆکەی وەک لە وانەی خولی while، ئێستا بە هەردوو پشکنینەکەوە:

A number from low to highژمارەیەک لە low تا highget_int_between.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please type a whole number.")


def get_int_between(prompt, low, high):
    while True:
        number = get_int(prompt)
        if low <= number <= high:
            return number
        print(f"Please type a number from {low} to {high}.")


digits = get_int_between("How many binary digits (2 or 3)? ", 2, 3)
print("You chose", digits)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 11

Step 1: get_int() makes sure it is a whole number.

هەنگاوی 1: get_int() دڵنیا دەبێتەوە کە .

Lineدێڕی 12-14

Step 2: an ordinary if checks the range; a bad number simply loops again.

هەنگاوی 2: ifـێکی ئاسایی سنوورەکان دەپشکنێت؛ ژمارەی خراپ تەنها دووبارە دەکاتەوە.

The binary converter project uses exactly this to fix its first version, which crashed when the user typed a word.

پڕۆژەی گۆڕینی دووانی ڕێک ئەمە بەکار دەهێنێت بۆ چاککردنی یەکەم وەشانی خۆی کە کاتێک وشەیەکی دەنووسی دەکەوت.

Quick checkپشکنینی خێراA user of get_int_between(…, 2, 3) types 5. What happens? get_int_between(…, 2, 3) 5 دەنووسێت. چی ڕوو دەدات؟

A safe input function: get_int()کردارێکی نێوخستەی سەلامەت: ⁦get_int()⁩

Check first, or just try?سەرەتا بپشکنە، یان تەنها هەوڵ بدە؟

Some programmers check before converting: if text.isdigit():. Python programmers usually just try, because the check and the conversion do not agree. This table was made by the program under it:

هەندێک بەرنامەساز پێش گۆڕین دەپشکنن: if text.isdigit():. بەرنامەسازانی زۆرجار تەنها هەوڵ دەدەن، چونکە پشکنینەکە و گۆڕینەکە یەک ناگرنەوە. ئەم خشتەیە ئەو دروستی کردووە کە لە ژێریدایە:

isdigit() against int()⁦isdigit()⁩ بەرامبەر ⁦int()⁩isdigit_vs_int.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
for text in ["42", "-5", " 7 ", "٣", "²", "4.0"]:
    try:
        value = int(text)
    except ValueError:
        value = "ValueError"
    print(repr(text), text.isdigit(), value)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Six inputs a user might type: a negative number, spaces, a Kurdish digit, a superscript ², a decimal.

شەش کە لەوانەیە بینووسێت: ، ، کوردی، ²ـی سەرەوە، .

  • "-5" and " 7 ": isdigit() says no, but int() converts them.
  • "²": isdigit() says yes, but int() raises ValueError. A program that trusted the check would crash.
  • "-5" و " 7 ": isdigit() دەڵێت نا، بەڵام int() دەیانگۆڕێت.
  • "²": isdigit() دەڵێت بەڵێ، بەڵام int() ValueError دروست دەکات. کە متمانەی بە پشکنینەکە کردبێت دەکەوێت.
Quick checkپشکنینی خێراWhich input makes isdigit() return True but int() fail?کام وا دەکات isdigit() True بگەڕێنێتەوە بەڵام int() سەرنەکەوێت؟

Raising your own exceptionsدروستکردنی هەڵاوێردەکانی خۆت

Your own functions can raise exceptions too, with raise. A function that gets an impossible value should not guess what to do; it raises an exception and lets the caller decide. The caller can catch it, or let the program stop with a clear message:

خۆشت دەتوانن بە raise دروست بکەن. کە مەحاڵ وەردەگرێت نابێت مەزەندە بکات چی بکات؛ دروست دەکات و بڕیارەکە بۆ بانگکەر جێ دەهێڵێت. بانگکەر دەتوانێت بیگرێت، یان ڕێگە بدات بە پەیامێکی ڕوون بوەستێت:

A bill cannot have negative teasپسوولە ناتوانێت چای سالبی هەبێتraise_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def bill(teas, price=500):
    if teas < 0:
        raise ValueError("the number of teas cannot be negative")
    return teas * price


print(bill(3))
try:
    print(bill(-2))
except ValueError as error:
    print("Error:", error)
print(bill(-1))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-3

raise ValueError("…") creates the exception with a message and raises it.

raise ValueError("…") بە پەیامێکەوە دروست دەکات و هەڵیدەدات.

Lineدێڕی 8-11

This caller catches it and prints the message.

ئەم بانگکەرە دەیگرێت و پەیامەکە چاپ دەکات.

Lineدێڕی 12

This caller does not: the program stops, and the traceback shows both the call and the raise line.

ئەم بانگکەرە نایگرێت: دەوەستێت و هەم بانگکردنەکە و هەم دێڕی raise پیشان دەدات.

Quick checkپشکنینی خێراWhy should bill(-2) raise an exception instead of returning 0?بۆچی bill(-2) دەبێت دروست بکات لەبری گەڕاندنەوەی 0؟

Checking your own assumptions: assertپشکنینی گریمانەکانی خۆت: assert

assert condition, "message" is a programmer's check that says this must be true here. If the condition is False, Python raises AssertionError with the message. Use it where a wrong value would mean a bug in your code, for example at the start of a function:

assert condition, "message" پشکنینی بەرنامەسازە و دەڵێت لێرەدا ئەمە دەبێت ڕاست بێت. ئەگەر False بێت، AssertionError لەگەڵ پەیامەکەدا دروست دەکات. لەو شوێنەدا بەکاری بهێنە کە هەڵە واتای بێت لە کۆدی خۆتدا، بۆ نموونە لە سەرەتای :

An assert at the start of a functionassert لە سەرەتای کردارێکداassert_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def side_of_square(area):
    assert area >= 0, "the area cannot be negative"
    return area ** 0.5


print(side_of_square(49))
print(side_of_square(-4))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

If area >= 0 is False, Python raises AssertionError with this message.

ئەگەر area >= 0 False بێت، AssertionError بەم پەیامەوە دروست دەکات.

Never use assert to check what a user types. Python leaves out every assert when it runs with the -O (optimise) option, and the same file then gives no error but a nonsense answer. For checks that must always run, use if with raise (Raising your own exceptions); asserts belong in tests, like the automatic test of the binary converter.

هەرگیز assert بۆ پشکنینی ئەوەی دەینووسێت بەکار مەهێنە. کاتێک بە هەڵبژاردەی -O (باشکردن) کار دەکات هەموو assertـێک لادەبات و هەمان ئیتر نادات بەڵکو وەڵامێکی بێمانا دەدات. بۆ ئەو پشکنینانەی دەبێت هەمیشە جێبەجێ ببن if لەگەڵ raise بەکار بهێنە (دروستکردنی هەڵاوێردەکانی خۆت)؛ شوێنی assert تاقیکردنەوەکانە، وەک تاقیکردنەوە خۆکارەکەی گۆڕەری دووانی.

assert_demo.py run with python3 -O⁦assert_demo.py⁩ کە بە ⁦python3 -O⁩ کاری پێ کراوە
7.0
(1.2246467991473532e-16+2j)

With -O the assert is gone: (-4) ** 0.5 quietly becomes a complex number.

بە -O assertـەکە نامێنێت: (-4) ** 0.5 بە بێدەنگی دەبێتە ژمارەیەکی ئاڵۆز.

Quick checkپشکنینی خێراWhy should assert not be used to reject bad user input?بۆچی نابێت assert بۆ ڕەتکردنەوەی خراپی بەکار بێت؟

Common mistakesهەڵە باوەکان

MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
A bare except:except:ـی ڕووتTypos are hidden; Ctrl+C is caught too.هەڵەی نووسین دەشاردرێتەوە؛ ⁦Ctrl+C⁩ـیش دەگیرێت.Name the exception: except ValueError:ناوی بهێنە: except ValueError:
Many lines inside tryزۆر دێڕ لەناو tryـداAn except may catch an error from the wrong line.لەوانەیە except لە دێڕی هەڵەوە بگرێت.Keep only the risky line in try; use else.تەنها دێڕە مەترسیدارەکە لە tryـدا بهێڵەرەوە؛ else بەکار بهێنە.
Using a variable after its assignment failedبەکارهێنانی دوای ئەوەی دانانەکەی سەرنەکەوتNameErrorNameErrorUse it in else, or loop until the input is valid.لە elseـدا بەکاری بهێنە، یان بکە تا دروست بێت.
Catching but not asking againگرتن بەبێ دووبارە پرسینەوەThe user gets only one chance. تەنها یەک هەل وەردەگرێت.Put the try in a while True: loop (get_int()).try بخەرە ناو while True: (get_int()).
Expecting try to catch a syntax errorچاوەڕوانی ئەوەی try بگرێتImpossible: Python cannot even start the program.مەحاڵە: تەنانەت ناتوانێت دەست پێ بکات.Fix the code.کۆدەکە چاک بکە.
try: with no except or finallytry: بەبێ except یان finallySyntaxErrorSyntaxErrorAdd at least one except (or a finally).لانیکەم یەک except (یان finally) زیاد بکە.
Thinking try checks meaningوا بزانیت try واتا دەپشکنێت0 picks the last mark with no error.0 بەبێ دوایین نمرە هەڵدەبژێرێت.Add your own if range check.پشکنینی سنووری خۆت بە if زیاد بکە.

Exercisesڕاهێنانەکان

Exerciseڕاهێنانget_float()get_float()

Write get_float(prompt), which asks until the user types a number that may have a decimal point. Use it to read kilos of apples and print the price at 1500 dinars a kilo.

get_float(prompt) بنووسە کە دەپرسێت تا ژمارەیەک بنووسێت کە لەوانەیە هەبێت. بەکاری بهێنە بۆ خوێندنەوەی کیلۆی سێو و چاپکردنی نرخەکەی بە کیلۆی ⁦1500⁩ دینار.

Show answerوەڵامەکە پیشان بدە
ex_get_float.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def get_float(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Please type a number, like 1.5")


kilos = get_float("How many kilos of apples? ")
print("You pay", kilos * 1500, "dinars")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

float() instead of int(); the error is still ValueError.

float() لەبری int()؛ هێشتا ValueErrorـە.

1,5 is rejected: Python numbers use a point, not a comma.

1,5 ڕەت دەکرێتەوە: ژمارەکانی خاڵ بەکار دەهێنن نەک کۆما.

ExerciseڕاهێنانA safe dividerدابەشکەرێکی سەلامەت

Read two numbers and print the first divided by the second. Handle text (ValueError) and division by zero (ZeroDivisionError) with two different messages, and print the result in else.

دوو ژمارە بخوێنەوە و یەکەمیان دابەشکراو بەسەر دووەمدا چاپ بکە. دەق (ValueError) و دابەشکردن بەسەر سفردا (ZeroDivisionError) بە دوو پەیامی جیاواز چارەسەر بکە و ئەنجامەکە لە elseـدا چاپ بکە.

Show answerوەڵامەکە پیشان بدە
ex_divide.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    a = float(input("First number: "))
    b = float(input("Second number: "))
    answer = a / b
except ValueError:
    print("Those were not numbers.")
except ZeroDivisionError:
    print("You cannot divide by zero.")
else:
    print(f"{a} / {b} = {answer}")
ExerciseڕاهێنانFix the trapداوەکە چاک بکە

This program crashes with NameError when the user types a word. Explain why and fix it.

ئەم کاتێک وشەیەک دەنووسێت بە NameError دەکەوێت. ڕوونی بکەرەوە بۆچی و چاکی بکە.

teas_trap.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    teas = int(input("How many teas? "))
except ValueError:
    print("That is not a whole number.")
print("You ordered", teas, "teas.")
Show answerوەڵامەکە پیشان بدە

When int() fails, teas is never assigned, but the last line uses it anyway. Move that line into else:

کاتێک int() سەرناکەوێت، teas هەرگیز وەرناگرێت، بەڵام دوایین دێڕ هەر بەکاری دەهێنێت. ئەو دێڕە بگوازەرەوە بۆ ناو else:

teas_else.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    teas = int(input("How many teas? "))
except ValueError:
    print("That is not a whole number.")
else:
    print("You ordered", teas, "teas.")
ExerciseڕاهێنانPredict the orderڕیزبەندییەکە پێشبینی بکە

Without running it, write the letters this program prints, in order.

بەبێ جێبەجێکردن، ئەو پیتانە بە ڕیز بنووسە کە ئەم چاپیان دەکات.

ex_order.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    print("A")
    x = int("5a")
    print("B")
except ValueError:
    print("C")
else:
    print("D")
finally:
    print("E")
print("F")
Show answerوەڵامەکە پیشان بدە
ex_order.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
try:
    print("A")
    x = int("5a")
    print("B")
except ValueError:
    print("C")
else:
    print("D")
finally:
    print("E")
print("F")

int("5a") fails, so B is skipped and C is printed; else (D) is skipped because there was an exception; finally (E) always runs; F comes after the whole statement.

int("5a") سەرناکەوێت، بۆیە بازی بەسەر Bـدا دەدرێت و C چاپ دەکرێت؛ بازی بەسەر else ⁦(D)⁩ـدا دەدرێت چونکە ڕووی دا؛ finally ⁦(E)⁩ هەمیشە جێبەجێ دەبێت؛ F دوای هەموو دێت.

ExerciseڕاهێنانAn average that skips bad marksتێکڕایەک کە نمرە خراپەکان پشتگوێ دەخات

Read marks until the user presses Enter on an empty line. Skip anything that is not a whole number (say which input was skipped), then print the average of the good marks.

نمرە بخوێنەوە تا لەسەر دێڕێکی بەتاڵ Enter دادەگرێت. هەر شتێک کە نەبێت پشتگوێ بخە (بڵێ کام پشتگوێ خرا)، پاشان تێکڕای نمرە باشەکان چاپ بکە.

Show answerوەڵامەکە پیشان بدە
ex_average.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
marks = []
while True:
    text = input("Mark (empty line to stop): ")
    if text == "":
        break
    try:
        marks.append(int(text))
    except ValueError:
        print("Skipped:", text)
if marks:
    print("Average:", sum(marks) / len(marks))
else:
    print("No marks.")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4-5

The empty line is the sentinel that ends the loop.

دێڕە بەتاڵەکە کە کۆتایی پێ دەهێنێت.

Lineدێڕی 6-9

try/except inside the loop: a bad entry is reported and the loop simply continues.

try/except لەناو : نووسینێکی خراپ ڕادەگەیەنرێت و بە سادەیی بەردەوام دەبێت.

Check: (80+90+70)/3=240/3=80.0(80 + 90 + 70) / 3 = 240 / 3 = 80.0.

پشکنین: (80+90+70)/3=240/3=80.0(80 + 90 + 70) / 3 = 240 / 3 = 80.0.

ExerciseڕاهێنانWhich room?کام ژوور؟

rooms = {"maths": 12, "python": 7, "english": 3}. Ask for a subject and print its room. Catch the KeyError for unknown subjects. Then think: how would rooms.get() do the same without try?

rooms = {"maths": 12, "python": 7, "english": 3}. داوای بابەتێک بکە و ژوورەکەی چاپ بکە. KeyError بۆ بابەتی نەناسراو بگرە. پاشان بیر بکەرەوە: rooms.get() چۆن هەمان کار بەبێ try دەکات؟

Show answerوەڵامەکە پیشان بدە
rooms.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
rooms = {"maths": 12, "python": 7, "english": 3}
subject = input("Subject: ")
try:
    print("Room", rooms[subject])
except KeyError:
    print("There is no room for", subject)

With get(): room = rooms.get(subject) gives None for an unknown subject, and if room is None: prints the message. Both ways are fine; Tuples, sets and dictionaries compares them.

بە get(): room = rooms.get(subject) بۆ بابەتی نەناسراو None دەدات و if room is None: پەیامەکە چاپ دەکات. هەردوو ڕێگاکە باشن؛ تاپڵەکان، کۆمەڵەکان و فەرهەنگەکان بەراوردیان دەکات.

ExerciseڕاهێنانSyntax error or exception?هەڵەی داڕستن یان هەڵاوێردە؟

Explain with examples: every syntax error is an exception, but not every exception is a syntax error. Then write one line that raises each of ImportError, OSError (the old IOError), NameError and ZeroDivisionError.

بە نموونەوە ڕوونی بکەرەوە: هەموو ، بەڵام هەموو نییە. پاشان بۆ هەر یەک لە ImportError، OSError (IOErrorـی کۆن)، NameError و ZeroDivisionError یەک دێڕ بنووسە کە دروستی بکات.

Show answerوەڵامەکە پیشان بدە

SyntaxError is one of Python's exception classes, so a syntax error is an exception. But Python raises it while it reads the code, before anything runs; every other exception happens while correct code is running. compile() reads code from a string, so it even lets a program catch a SyntaxError:

SyntaxError یەکێکە لە جۆرەکانی لە ، بۆیە . بەڵام کاتی خوێندنەوەی کۆدەکە دروستی دەکات، پێش ئەوەی هیچ شتێک جێبەجێ ببێت؛ هەموو تر لە کاتی کارکردنی کۆدی دروستدا ڕوو دەدەن. compile() کۆد لە دەخوێنێتەوە، بۆیە ڕێگە دەدات تەنانەت SyntaxErrorـیش بگرێت:

ex_syntax2.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
print(issubclass(SyntaxError, Exception))
try:
    compile("print('hi'", "test.py", "exec")   # a missing bracket
except SyntaxError as error:
    print("Caught:", type(error).__name__)
LineدێڕExceptionWhyبۆچی
import mathsModuleNotFoundErrorno such module; a kind of ImportError وا نییە؛ جۆرێکی ImportError
open("missing.txt")FileNotFoundErrorno such file; a kind of OSError (IOError is OSError is True) وا نییە؛ جۆرێکی OSError (IOError is OSError دەکاتە True)
print(prise)NameErrorthe name was never given a valueناوەکە هەرگیز پێ نەدراوە
print(10 / 0)ZeroDivisionErrordividing by zeroدابەشکردن بەسەر سفردا
Exerciseڕاهێنانdivide() that raises, tested with assert⁦divide()⁩ کە هەڵاوێردە دروست دەکات، بە assert تاقیکراوەتەوە

Write divide(a, b) that raises ZeroDivisionError with a clear message when b is 0. Test two normal cases with assert, catch the error for b = 0, and say in one sentence each what raising (throwing), catching and exception handling mean.

divide(a, b) بنووسە کە کاتێک b 0ـە ZeroDivisionError بە پەیامێکی ڕوونەوە دروست دەکات. دوو حاڵەتی ئاسایی بە assert تاقی بکەرەوە، بۆ b = 0 بگرە و بە یەک ڕستە بۆ هەر یەکێک بڵێ دروستکردن (هەڵدان)، گرتن و واتای چییە.

Show answerوەڵامەکە پیشان بدە
ex_divide_assert.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("the second number must not be 0")
    return a / b


assert divide(10, 4) == 2.5
assert divide(-9, 3) == -3.0
try:
    divide(1, 0)
except ZeroDivisionError as error:
    print("Caught:", error)
print("All tests passed.")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 7-8

If divide() ever gave a wrong answer, an assert would stop with AssertionError.

ئەگەر divide() وەڵامێکی هەڵە بدات، assert بە AssertionError دەوەستێت.

Raising (throwing): creating an exception object and sending it off, by Python or by raise. Catching: an except that matches receives it and runs. Exception handling: planning these try/except paths so the program reacts sensibly instead of crashing.

دروستکردن (هەڵدان): دروستکردنی و ناردنی، لەلایەن یان raiseـەوە. گرتن: exceptـێکی گونجاو وەریدەگرێت و جێبەجێ دەبێت. : پلاندانانی ئەم ڕێگایانەی try/except تا لەبری کەوتن بە ژیرانە وەڵام بداتەوە.

ExerciseڕاهێنانMake math.sqrt() fail in two waysmath.sqrt() بە دوو ڕێگا تووشی هەڵە بکە

Call math.sqrt() with two arguments, then with -1. Catch each error, print its type and message, and add a finally that reports the end of each test.

math.sqrt() جارێک بە دوو و جارێک بە -1 بانگ بکە. هەر بگرە، جۆر و پەیامەکەی چاپ بکە و finallyـێک زیاد بکە کە کۆتایی هەر تاقیکردنەوەیەک ڕادەگەیەنێت.

Show answerوەڵامەکە پیشان بدە
ex_sqrt.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import math

try:
    print(math.sqrt(16, 2))           # two arguments instead of one
except TypeError as error:
    print("TypeError:", error)
finally:
    print("Test 1 finished.")

try:
    print(math.sqrt(-1))              # no real square root
except ValueError as error:
    print("ValueError:", error)
finally:
    print("Test 2 finished.")

A wrong number of arguments is a TypeError, not a ValueError (some books say otherwise). A value of the right type that the function cannot use, such as a negative number here, is a ValueError. finally runs after both.

ژمارەیەکی هەڵەی TypeErrorـە نەک ValueError (هەندێک کتێب پێچەوانەکەی دەڵێن). بە جۆری دروست کە ناتوانێت بەکاری بهێنێت، وەک لێرەدا، ValueErrorـە. finally دوای هەردووکیان جێبەجێ دەبێت.

Summaryپوختە

  • An exception is an error raised while the program runs. Unhandled, it stops the program with a traceback.
  • try: holds the risky line; except SomeError: handles that error; the rest of try is skipped when it happens.
  • else: runs only after success; finally: runs in every case.
  • An exception travels back through the calls (the call stack) until an except catches it.
  • Name the exceptions you expect, one except each or a tuple: except (ValueError, IndexError):. Avoid a bare except:.
  • get_int(): while True: + try: return int(input(prompt)) + except ValueError: asks until the input is valid.
  • raise ValueError("message") lets your own functions report impossible values.
  • assert checks your own assumptions; python -O removes it, so never use it for user input.
  • کە لە کاتی کارکردنی دروست دەبێت. ئەگەر چارەسەر نەکرێت، بە دەوەستێنێت.
  • try: دێڕە مەترسیدارەکە هەڵدەگرێت؛ except SomeError: ئەو چارەسەر دەکات؛ کاتێک ڕوو دەدات بازی بەسەر پاشماوەی tryـدا دەدرێت.
  • else: تەنها دوای سەرکەوتن جێبەجێ دەبێت؛ finally: لە هەموو حاڵەتێکدا.
  • بە بانگکردنەکاندا () دەگەڕێتەوە تا exceptـێک دەیگرێت.
  • ناوی چاوەڕوانکراو بهێنە، بۆ هەر یەکێک exceptـێک یان : except (ValueError, IndexError):. خۆت لە except:ـی ڕووت بپارێزە.
  • get_int(): while True: + try: return int(input(prompt)) + except ValueError: دەپرسێت تا دروست بێت.
  • raise ValueError("message") ڕێگە بە خۆت دەدات مەحاڵ ڕابگەیەنن.
  • assert گریمانەکانی خۆت دەپشکنێت؛ python -O لای دەبات، بۆیە هەرگیز بۆ بەکاری مەهێنە.
Review questionsپرسیارەکانی پێداچوونەوە
Can try/except catch a missing colon?ئایا try/except نەبوونی دوو خاڵ دەگرێت؟

No. That is a syntax error: Python finds it before the program starts.

نەخێر. ئەوە : پێش دەستپێکردنی دەیدۆزێتەوە.

Why does get_int() need a loop?بۆچی get_int() پێویستی بە خول هەیە؟

Without it the user gets only one chance; the loop asks again until int() succeeds and return leaves.

بەبێ ئەو تەنها یەک هەل وەردەگرێت؛ دیسان دەپرسێت تا int() سەردەکەوێت و return دەردەچێت.

Why is a bare except: dangerous?بۆچی except:ـی ڕووت مەترسیدارە؟

It hides unexpected bugs such as a NameError, and it even catches Ctrl+C.

چاوەڕواننەکراوەکانی وەک NameError دەشارێتەوە و تەنانەت ⁦Ctrl+C⁩ـیش دەگرێت.

Videoڤیدیۆ

Watch a videoسەیری ڤیدیۆیەک بکە

A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.

Exceptions in Python || Python Tutorial || Learn Python ProgrammingSocratica · Englishئینگلیزی · 292K viewsبینین · 9.5K likesلایک

What an exception is, the common built-in exceptions, and the four parts try, except, else and finally, shown on a worked example.

چییە، باوی ناو و چوار بەشی try، except، else و finally لەسەر نموونەیەکی چارەسەرکراو.

A 9-minute overview of the whole lesson: common exceptions (1:14), built-in exceptions (3:43), handling them with try, except, else and finally (4:32).

پێداچوونەوەیەکی 9 خولەکی بۆ هەموو وانەکە: باو ⁦(1:14)⁩، ئامادە ⁦(3:43)⁩ و بە try، except، else و finally ⁦(4:32)⁩.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Reading and Writing Filesخوێندنەوە و نووسینی فایلەکان

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.