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() بنووسە کە دەپرسێت تا دروست بێت و خۆت دروست بکە.
What you will learnچی فێر دەبیت
- Tell exceptions apart from syntax errors and explain what happens when an exception is not handled.
- Catch exceptions with
tryandexcept, and follow which lines run and which are skipped. - Use
elseandfinally, and keep thetryblock small. - Catch specific exceptions (one or several), read their message with
as, and avoid a bareexcept:. - Write
get_int()andget_int_between()to read numbers safely, and raise your own exceptions withraise. - Explain how an exception travels through the call stack, and use
assertfor 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(...)) بەکار دەهێنێت. تا ژمارە بنووسێت کار دەکات. ئەگەر لەبری ئەوە وشەیەک بنووسێت، لە ناوەڕاستدا دەوەستێت:
teas = int(input("How many teas? "))
print("That is", teas * 500, "dinars.")How many teas? two
Traceback (most recent call last):
File "teas_crash.py", line 1, in <module>
teas = int(input("How many teas? "))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'two'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 دروست دەکات. هیچ شتێک لە مامەڵەی لەگەڵ ناکات، بۆیە دەوەستێت و چاپ دەکات (هەڵەکان و کرمەکوژی پیشانی دەدات چۆن بیخوێنیتەوە). بۆ بە سادەیی کەوتووە. لەم وانەیەدا فێری دەبیت: گرتنیان و وەڵامدانەوەیان، لەبری کەوتن.
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#ـدا.
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ـێک ئەم جۆرە کێشەیە نەناسێت، یارییەکە هەڵدەوەشێتەوە: دەوەستێت.
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 لەوێ ڕووی دا چی بکرێت. ئەمە دیسان داواکارییەکەی چایە، دوو جار کاری پێ کراوە:
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!")How many teas? 3 That is 1500 dinars. Thank you! How many teas? two Please type a whole number, like 3. Thank you!
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-3
The
tryblock: the risky conversion and the line that uses its result.بلۆکی
try: گۆڕینە مەترسیدارەکە و ئەو دێڕەی ئەنجامەکەی بەکار دەهێنێت.- Lineدێڕی 4-5
The
exceptblock runs only if aValueErrorhappened insidetry.بلۆکی
exceptتەنها کاتێک جێبەجێ دەبێت کەValueErrorلەناوtryـدا ڕووی دابێت.- Lineدێڕی 6
After either path, the program carries on normally.
دوای هەر یەک لە دوو ڕێگاکە، بە ئاسایی بەردەوام دەبێت.
- Run tryجێبەجێکردنی try
Python runs the lines of the
tryblock one by one.دێڕەکانی بلۆکی
tryیەک بە یەک جێبەجێ دەکات. - No problemبێ کێشە
If no exception happens, the
exceptblock is skipped and the program continues after it.ئەگەر هیچ ڕوو نەدات، بازی بەسەر بلۆکی
exceptـدا دەدرێت و لە دوای ئەوەوە بەردەوام دەبێت. - A problem that is handledکێشەیەک کە چارەسەر دەکرێت
If a line raises an exception, the rest of
tryis skipped. Python looks at theexceptclauses. If one names this kind of exception, its block runs, and then the program continues after the whole statement.ئەگەر دێڕێک دروست بکات، پاشماوەی
tryبازی بەسەردا دەدرێت. سەیری بەشەکانیexceptدەکات. ئەگەر یەکێکیان ناوی ئەم جۆرە هێنابێت، بلۆکەکەی جێبەجێ دەبێت و پاشان لە دوای هەموو بەردەوام دەبێت. - A problem nobody handlesکێشەیەک کە کەس چارەسەری ناکات
If no
exceptmatches, the exception is not handled and the program stops with a traceback, as before.ئەگەر هیچ
exceptـێک نەگونجێت، چارەسەر ناکرێت و وەک پێشتر بە دەوەستێت.
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:
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.")How many teas? two
That is not a whole number.
Traceback (most recent call last):
File "teas_trap.py", line 5, in <module>
print("You ordered", teas, "teas.")
^^^^
NameError: name 'teas' is not definedExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
int("two")fails, soteas = …never happens.int("two")سەرناکەوێت، بۆیەteas = …هەرگیز ڕوو نادات.- Lineدێڕی 5
This line runs anyway, but
teasdoes 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 بێگومان هەیە:
try:
teas = int(input("How many teas? "))
except ValueError:
print("That is not a whole number.")
else:
print("You ordered", teas, "teas.")How many teas? two That is not a whole number. How many teas? 4 You ordered 4 teas.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5-6
The success path lives in
else, outside the protectedtryblock.ڕێگای سەرکەوتن لە
elseـدایە، لە دەرەوەی بلۆکی پارێزراویtry.
Catching an exception: try and exceptگرتنی هەڵاوێردەیەک: try و except
Where does Python look for an except?Python لە کوێ بەدوای exceptـدا دەگەڕێت؟
When a line fails, Python creates an exception object that holds the error's type and message, and throws it (Python's word is raises). Then it looks for a matching except: first in the function where the error happened, then in the function that called it, then in that function's caller, back along the call stack (The call stack). Finding one is called catching the exception. If no call has one, the program stops and the traceback lists the calls the exception passed through.
کاتێک دێڕێک سەرناکەوێت، دروست دەکات کە جۆر و پەیامی هەڵدەگرێت و هەڵیدەدات (وشەی raiseـە). پاشان بەدوای exceptـێکی گونجاودا دەگەڕێت: سەرەتا لەو تێدا ڕووی دا، پاشان لەو بانگی کردووە، پاشان لە بانگکەری ئەو، بە درێژایی (ستاکی بانگکردن). دۆزینەوەی ئەو exceptـە پێی دەوترێت گرتنی . ئەگەر هیچ بانگکردنێک نەیبێت، دەوەستێت و ئەو بانگکردنانە ڕیز دەکات کە پێیاندا تێپەڕیوە.
exceptـێک دەیگرێت.CêITdef read_count(text):
return int(text) # the ValueError starts here
def order(text):
count = read_count(text) # no try here: the exception passes up
return count * 500
try:
print(order("3"))
print(order("two"))
print("This line is skipped.")
except ValueError as error:
print("Caught in the main program:", error)1500 Caught in the main program: invalid literal for int() with base 10: 'two'
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
int("two")raises theValueErrorinsideread_count().int("two")لەناوread_count()ـداValueErrorدروست دەکات.- Lineدێڕی 6
order()has notry: the exception leaves it at once.order()tryـی نییە: یەکسەر لێی دەردەچێت.- Lineدێڕی 12-15
The main program's
exceptcatches it; line 13 is skipped.exceptـی سەرەکییەکە دەیگرێت؛ بازی بەسەر دێڕی 13ـدا دەدرێت.
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ـی هەبێت، یەکێک بۆ هەر کێشەیەک کە چاوەڕێی دەکەیت. لە سەرەوە بۆ خوارەوە دەیانپشکنێت و تەنها یەکەمیان کە بگونجێت جێبەجێ دەکات. لێرەدا پسوولەیەک لە چایخانەیەک بەسەر هاوڕێکاندا دابەش دەکرێت:
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.")Total bill (dinars): 6000 Number of people: 4 Each person pays 1500 dinars. Total bill (dinars): 6000 Number of people: 0 The number of people cannot be zero. Total bill (dinars): 6000 Number of people: four Please type whole numbers only.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
Dividing by 0 raises
ZeroDivisionError.دابەشکردن بەسەر 0ـدا
ZeroDivisionErrorدروست دەکات.- Lineدێڕی 5-8
Two
exceptclauses, each with its own clear message.دوو بەشی
except، هەر یەکەیان بە پەیامێکی ڕوونی خۆیەوە.- Lineدێڕی 9-10
else: only when both numbers were fine.else: تەنها کاتێک هەردوو ژمارەکە باش بوون.
| Exception | Typical causeهۆی باو | Exampleنموونە |
|---|---|---|
ValueError | right type, wrong valueجۆری ڕاست، هەڵە | int("two") |
ZeroDivisionError | dividing by zeroدابەشکردن بەسەر سفردا | 6000 / 0 |
KeyError | a dictionary key that does not exist کە نییە | prices["milk"] |
IndexError | a list position that does not existشوێنێکی کە نییە | marks[5] |
TypeError | mixing types that do not fitتێکەڵکردنی جۆرگەلێک کە ناگونجێن | "Age: " + 19 |
FileNotFoundError | a file that does not exist کە بوونی نییە | open("missing.txt") |
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):. لێرەدا یەکێک لە سێ نمرە بە ژمارەکەی هەڵدەبژێرێت:
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.")Which mark (1-3)? 2 Mark: 91 Which mark (1-3)? 5 Please type 1, 2 or 3. Which mark (1-3)? x Please type 1, 2 or 3. Which mark (1-3)? 0 Mark: 64
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
marks[position - 1]: typing 5 asks for index 4, which raisesIndexError.marks[position - 1]: نووسینی 5 داوای 4 دەکات کەIndexErrorدروست دەکات.- Lineدێڕی 5
The tuple catches both
ValueError(not a number) andIndexError(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 ناوێک بدە بە . ناوەکە ئۆبجێکتی هەڵدەگرێت؛ چاپکردنی پەیامەکەی چاپ دەکات:
try:
number = int(input("A whole number: "))
except ValueError as error:
print("Problem:", error)
else:
print("Double:", number * 2)A whole number: 4.5 Problem: invalid literal for int() with base 10: '4.5' A whole number: 21 Double: 42
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:
زۆر ئامادەی تریشی هەیە. ئەمانە ئەوانەن کە فێرخواز دواتر تووشیان دەبێت؛ ناوی هەر یەکەیان دەڵێت چی هەڵە بوو:
| Exception | Raised whenکەی دروست دەبێت | Exampleنموونە |
|---|---|---|
ImportError | a module, or a name inside it, cannot be loaded; ModuleNotFoundError is its kind for a missing module، یان ناوێکی ناوی، بار ناکرێت؛ ModuleNotFoundError جۆرەکەیەتی بۆ کە نییە | import maths |
EOFError | input() 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() |
KeyboardInterrupt | the user presses the interrupt key, Ctrl+C (Stopping the loop with Ctrl+C) کلیلی ڕاگرتن دادەگرێت، Ctrl+C (وەستاندنی خولەکە بە Ctrl+C) | Ctrl+C |
OverflowError | a decimal (float) result is too big to store; whole numbers never overflow in Pythonئەنجامێکی زۆر گەورەیە بۆ هەڵگرتن؛ لە هەرگیز تووشی نابن | math.exp(1000) |
OSError | a file or folder problem; FileNotFoundError and PermissionError are its kinds (Errors you will meet)کێشەیەکی یان ؛ FileNotFoundError و PermissionError دوو جۆری ئەون (چەند هەڵەیەک کە تووشیان دەبیت) | open("missing.txt") |
SyntaxError | the code breaks Python's grammar (IndentationError is one kind); raised before the program starts (Syntax errors)کۆدەکە یاساکانی زمانی دەشکێنێت (IndentationError جۆرێکیەتی)؛ پێش دەستپێکردنی دروست دەبێت (هەڵەکانی داڕستن) | if x == 1 |
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)ModuleNotFoundError - No module named 'maths' OverflowError - math range error FileNotFoundError - [Errno 2] No such file or directory: 'missing.txt'
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
except ImportErroralso catchesModuleNotFoundError: catching a family catches all its kinds.except ImportErrorModuleNotFoundErrorـیش دەگرێت: گرتنی بنەماڵەیەک هەموو جۆرەکانی دەگرێت.- Lineدێڕی 6
type(error).__name__is the name of the exception's class.type(error).__name__ناوی جۆری .
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 نووسراوە. ژمارەیەکی دروست دەنووسێت:
exceptـی ڕووت هەڵەیەکی نووسین دەشارێتەوەbare_except.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەtry:
teas = int(input("How many teas? "))
print("Total:", teas * prise)
except:
print("Please type a whole number.")How many teas? 3 Please type a whole number.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
prisedoes not exist: aNameError.priseبوونی نییە:NameError.- Lineدێڕی 4-5
The bare
exceptcatches theNameErrorand prints a message that is simply wrong.exceptـە ڕووتەکەNameErrorدەگرێت و پەیامێک چاپ دەکات کە بە ڕوونی هەڵەیە.
Name the exception you expect, and Python shows the real bug at once:
ناوی ئەو بهێنە کە چاوەڕێی دەکەیت، ئەوسا یەکسەر ڕاستەقینەکە پیشان دەدات:
try:
teas = int(input("How many teas? "))
print("Total:", teas * prise)
except ValueError:
print("Please type a whole number.")How many teas? 3
Traceback (most recent call last):
File "named_except.py", line 3, in <module>
print("Total:", teas * prise)
^^^^^
NameError: name 'prise' is not defined. Did you mean: 'print'?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 دەبینیت.
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، لە هەموو حاڵەتێکدا جێبەجێ دەبێت: دوای سەرکەوتن، دوای کە چارەسەر کراوە و تەنانەت کاتێک چارەسەر نەکراوە (پێش ئەوەی بوەستێت). شوێنی کاری پاککردنەوەیە، وەک داخستنی یان ماڵئاوایی.
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)divide(10, 4) else: the result is 2.5 finally: this always runs divide(10, 0) except: cannot divide by zero finally: this always runs
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
The protected line: dividing by 0 raises
ZeroDivisionError.دێڕە پارێزراوەکە: دابەشکردن بەسەر 0ـدا
ZeroDivisionErrorدروست دەکات.- Lineدێڕی 6-7
elseprints the result only after a successful division.elseتەنها دوای دابەشکردنێکی سەرکەوتوو ئەنجامەکە چاپ دەکات.- Lineدێڕی 8-9
finallyprints 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ئارەزوومەندانە |
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: و هەر کە باش بوو لە دەربچۆ. کە لە پێچرایەوە، دەبێتە ئامرازێک کە بۆ هەموو ئەو ژمارانەی دەیانخوێننەوە بەکاری بهێنیت:
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")How many teas? two Please type a whole number. How many teas? 3.5 Please type a whole number. How many teas? 3 Price of one tea: 500 Total: 1500 dinars
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
An endless loop: it ends only through
return.: تەنها بە
returnکۆتایی دێت.- Lineدێڕی 5
If
int()succeeds,returnhands 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.
ئێستا سەرەکییەکە کورتە و هەرگیز بە ژمارەیەکی خراپ ناکەوێت.


int() سەرناکەوێت، لە دێڕە سەرنەکەوتووەکەوە باز دەداتە except؛ پاشان دیسان دەپرسێت.CêITBy the way: int() accepts any Unicode decimal digits, so a user who types Kurdish (Eastern Arabic) digits is fine too:
لە پەراوێزدا: int() هەر وەردەگرێت کە بە داینابێت، بۆیە کە ژمارەی کوردی (عەرەبیی ڕۆژهەڵاتی) دەنووسێت کێشەی نییە:
How many teas? ٣ Price of one tea: ٥٠٠ Total: 1500 dinars
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 تێدەپەڕێت و دەوەستێت، وەک دەیویست:
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))
^^^^^^^^^^^^^
KeyboardInterruptNow 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 وەک وەڵامێکی هەڵە قووت دەدرێت و هەموو جارێک دیسان دەپرسێتەوە:
except:ـی ڕووت 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? ")How many teas? two Please type a whole number. How many teas? ^CPlease type a whole number. How many teas? ^CPlease type a whole number. How many teas? 3
Both runs were made in a real terminal (Python 3.12).
هەردوو کارپێکردنەکە لە ڕاستەقینەدا کراون (Python 3.12).
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
Catches everything,
KeyboardInterruptincluded.هەموو شتێک دەگرێت،
KeyboardInterruptـیش.
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، ئێستا بە هەردوو پشکنینەکەوە:
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)How many binary digits (2 or 3)? two Please type a whole number. How many binary digits (2 or 3)? 5 Please type a number from 2 to 3. How many binary digits (2 or 3)? 3 You chose 3
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
ifchecks 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.
پڕۆژەی گۆڕینی دووانی ڕێک ئەمە بەکار دەهێنێت بۆ چاککردنی یەکەم وەشانی خۆی کە کاتێک وشەیەکی دەنووسی دەکەوت.
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():. بەرنامەسازانی زۆرجار تەنها هەوڵ دەدەن، چونکە پشکنینەکە و گۆڕینەکە یەک ناگرنەوە. ئەم خشتەیە ئەو دروستی کردووە کە لە ژێریدایە:
for text in ["42", "-5", " 7 ", "٣", "²", "4.0"]:
try:
value = int(text)
except ValueError:
value = "ValueError"
print(repr(text), text.isdigit(), value)'42' True 42 '-5' False -5 ' 7 ' False 7 '٣' True 3 '²' True ValueError '4.0' False ValueError
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, butint()converts them."²":isdigit()says yes, butint()raisesValueError. A program that trusted the check would crash.
"-5"و" 7 ":isdigit()دەڵێت نا، بەڵامint()دەیانگۆڕێت."²":isdigit()دەڵێت بەڵێ، بەڵامint()ValueErrorدروست دەکات. کە متمانەی بە پشکنینەکە کردبێت دەکەوێت.
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 دروست بکەن. کە مەحاڵ وەردەگرێت نابێت مەزەندە بکات چی بکات؛ دروست دەکات و بڕیارەکە بۆ بانگکەر جێ دەهێڵێت. بانگکەر دەتوانێت بیگرێت، یان ڕێگە بدات بە پەیامێکی ڕوون بوەستێت:
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))1500
Error: the number of teas cannot be negative
Traceback (most recent call last):
File "raise_demo.py", line 12, in <module>
print(bill(-1))
^^^^^^^^
File "raise_demo.py", line 3, in bill
raise ValueError("the number of teas cannot be negative")
ValueError: the number of teas cannot be negativeExplain 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
raiseline.ئەم بانگکەرە نایگرێت: دەوەستێت و هەم بانگکردنەکە و هەم دێڕی
raiseپیشان دەدات.
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 لەگەڵ پەیامەکەدا دروست دەکات. لەو شوێنەدا بەکاری بهێنە کە هەڵە واتای بێت لە کۆدی خۆتدا، بۆ نموونە لە سەرەتای :
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))7.0
Traceback (most recent call last):
File "assert_demo.py", line 7, in <module>
print(side_of_square(-4))
^^^^^^^^^^^^^^^^^^
File "assert_demo.py", line 2, in side_of_square
assert area >= 0, "the area cannot be negative"
^^^^^^^^^
AssertionError: the area cannot be negativeExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
If
area >= 0isFalse, Python raisesAssertionErrorwith this message.ئەگەر
area >= 0Falseبێت،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 تاقیکردنەوەکانە، وەک تاقیکردنەوە خۆکارەکەی گۆڕەری دووانی.
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 بە بێدەنگی دەبێتە ژمارەیەکی ئاڵۆز.
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بەکارهێنانی دوای ئەوەی دانانەکەی سەرنەکەوت | NameErrorNameError | Use 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 یان finally | SyntaxErrorSyntaxError | Add 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ڕاهێنانەکان
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وەڵامەکە پیشان بدە
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")How many kilos of apples? one and a half Please type a number, like 1.5 How many kilos of apples? 1,5 Please type a number, like 1.5 How many kilos of apples? 1.5 You pay 2250.0 dinars
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
float()instead ofint(); the error is stillValueError.float()لەبریint()؛ هێشتاValueErrorـە.
1,5 is rejected: Python numbers use a point, not a comma.
1,5 ڕەت دەکرێتەوە: ژمارەکانی خاڵ بەکار دەهێنن نەک کۆما.
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وەڵامەکە پیشان بدە
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}")First number: 7 Second number: 2 7.0 / 2.0 = 3.5 First number: 7 Second number: 0 You cannot divide by zero. First number: seven Those were not numbers.
This program crashes with NameError when the user types a word. Explain why and fix it.
ئەم کاتێک وشەیەک دەنووسێت بە NameError دەکەوێت. ڕوونی بکەرەوە بۆچی و چاکی بکە.
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:
try:
teas = int(input("How many teas? "))
except ValueError:
print("That is not a whole number.")
else:
print("You ordered", teas, "teas.")How many teas? two That is not a whole number. How many teas? 4 You ordered 4 teas.
Without running it, write the letters this program prints, in order.
بەبێ جێبەجێکردن، ئەو پیتانە بە ڕیز بنووسە کە ئەم چاپیان دەکات.
try:
print("A")
x = int("5a")
print("B")
except ValueError:
print("C")
else:
print("D")
finally:
print("E")
print("F")Show answerوەڵامەکە پیشان بدە
try:
print("A")
x = int("5a")
print("B")
except ValueError:
print("C")
else:
print("D")
finally:
print("E")
print("F")A C E 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 دوای هەموو دێت.
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وەڵامەکە پیشان بدە
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.")Mark (empty line to stop): 80 Mark (empty line to stop): ninety Skipped: ninety Mark (empty line to stop): 90 Mark (empty line to stop): 70 Mark (empty line to stop): Average: 80.0
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4-5
The empty line is the sentinel that ends the loop.
دێڕە بەتاڵەکە کە کۆتایی پێ دەهێنێت.
- Lineدێڕی 6-9
try/exceptinside the loop: a bad entry is reported and the loop simply continues.try/exceptلەناو : نووسینێکی خراپ ڕادەگەیەنرێت و بە سادەیی بەردەوام دەبێت.
Check: .
پشکنین: .
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 = {"maths": 12, "python": 7, "english": 3}
subject = input("Subject: ")
try:
print("Room", rooms[subject])
except KeyError:
print("There is no room for", subject)Subject: python Room 7 Subject: art There is no room for art
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: پەیامەکە چاپ دەکات. هەردوو ڕێگاکە باشن؛ تاپڵەکان، کۆمەڵەکان و فەرهەنگەکان بەراوردیان دەکات.
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ـیش بگرێت:
print(issubclass(SyntaxError, Exception))
try:
compile("print('hi'", "test.py", "exec") # a missing bracket
except SyntaxError as error:
print("Caught:", type(error).__name__)True Caught: SyntaxError
| Lineدێڕ | Exception | Whyبۆچی |
|---|---|---|
import maths | ModuleNotFoundError | no such module; a kind of ImportError وا نییە؛ جۆرێکی ImportError |
open("missing.txt") | FileNotFoundError | no such file; a kind of OSError (IOError is OSError is True) وا نییە؛ جۆرێکی OSError (IOError is OSError دەکاتە True) |
print(prise) | NameError | the name was never given a valueناوەکە هەرگیز پێ نەدراوە |
print(10 / 0) | ZeroDivisionError | dividing by zeroدابەشکردن بەسەر سفردا |
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وەڵامەکە پیشان بدە
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.")Caught: the second number must not be 0 All tests passed.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 7-8
If
divide()ever gave a wrong answer, an assert would stop withAssertionError.ئەگەر
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 تا لەبری کەوتن بە ژیرانە وەڵام بداتەوە.
math.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وەڵامەکە پیشان بدە
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.")TypeError: math.sqrt() takes exactly one argument (2 given) Test 1 finished. ValueError: math domain error 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 oftryis 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
exceptcatches it. - Name the exceptions you expect, one
excepteach or a tuple:except (ValueError, IndexError):. Avoid a bareexcept:. 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.assertchecks your own assumptions;python -Oremoves 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لای دەبات، بۆیە هەرگیز بۆ بەکاری مەهێنە.
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.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
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زاراوە سەرەکییەکان
Reading and Writing Filesخوێندنەوە و نووسینی فایلەکان
Related lecturesوانە پەیوەندیدارەکان
- Return Values and Noneنرخە گەڕاوەکان و None
- Tuples, Sets and Dictionariesتاپڵەکان، کۆمەڵەکان و فەرهەنگەکان
- Project: Binary to Decimal Converterپڕۆژیلە: گۆڕینی دووانی بۆ دەیی
- The Python You Need for the AI Labsئەو Pythonـەی بۆ تاقیگەکانی ژیریی دەستکرد پێویستە
- Reading and Writing Filesخوێندنەوە و نووسینی فایلەکان
- Recursionخۆبانگکردنەوە
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- Python Tutorial 8: Errors and Exceptions (8.3 Handling exceptions, 8.4 Raising, 8.7 Clean-up actions)
- Python Library: Built-in exceptions (ValueError, ZeroDivisionError, KeyError, IndexError, KeyboardInterrupt, hierarchy)
- CS50's Introduction to Programming with Python, lecture 3 notes (exceptions, get_int)
- PEP 8: Programming recommendations (specific exceptions, small try clauses)
- Python Library: Built-in functions — int() (accepted digits and bases)
- Python Language Reference: the assert statement (removed under -O)
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.