பாடம் 1 / 5 · Errors-ம் Files-ம் · படிக்க 3 min · புதுப்பிக்கப்பட்டது
try, except வெச்சு errors-ஐ கையாளுறது
Program crash ஆகாம மீண்டு வர, error-ஐ பிடிக்கிறது.
Program ஓடும்போது ஏதாவது தப்பானா, Python ஒரு exception-ஐ raise பண்ணும். கையாளலன்னா traceback-ஓட program நின்னுடும். try-க்குள்ள வெச்சா, அதுக்கு பதிலா என்ன நடக்கணும்னு நீங்க முடிவு பண்ணலாம்.
values = ["42", "abc", "7"]
for text in values:
try:
number = int(text)
print(number * 2)
except ValueError:
print(f"'{text}' is not a number")
84
'abc' is not a number
14
தப்பான value கையாளப்பட்டு, loop அடுத்ததுக்கு போச்சு. நீங்க எதிர்பார்க்கிற exception-ஓட பேரை சொல்லுங்க — இங்க ValueError; number இல்லாத text-க்கு int() raise பண்றது அதுதான்.
else, finally, பல excepts
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError as e:
return f"Bad input: {e}"
else:
return result
finally:
print("checked", a, b)
print(safe_divide(10, 2))
print(safe_divide(1, 0))
print(safe_divide("1", 2))
checked 10 2
5.0
checked 1 0
Cannot divide by zero
checked 1 2
Bad input: unsupported operand type(s) for /: 'str' and 'int'
- ஒவ்வொரு
except-ம் ஒரு வகை error-ஐ கையாளும்; முதல்ல பொருந்துறது ஓடும். as eexception-ஐ வெச்சுக்கும், அதோட message-ஐ காட்டலாம்.elseஎதுவும் தப்பாகலன்னா மட்டும் ஓடும்.finallyஎன்ன நடந்தாலும் ஓடும் — return-க்கு அப்புறம் கூட. சுத்தம் பண்ற வேலைக்கு use பண்ணுங்க.
சரியான பதில் வர்ற வரைக்கும் கேட்கிறது
while True:
try:
age = int(input("Age: "))
break
except ValueError:
print("Please type a whole number.")
print("Thanks, you are", age)
Age: twenty
Please type a whole number.
Age: 20
Thanks, you are 20
Warning
Exception பேர் இல்லாம வெறும் except: எழுதவே கூடாது. அது உங்க சொந்த typos-ஐயும் — தப்பா எழுதின variable மாதிரி — பிடிச்சு சத்தமில்லாம மறைச்சிடும். எதிர்பார்க்கிற குறிப்பிட்ட exception-ஐ மட்டும் பிடிங்க.
அடிக்கடி சந்திக்கிற exceptions
ValueError— type சரி, value தப்பு,int("abc")மாதிரி.TypeError— type தப்பு,"a" + 1மாதிரி.KeyError/IndexError— இல்லாத dictionary key அல்லது list position.ZeroDivisionError,FileNotFoundError,NameError.
finally block எப்போ ஓடும்?
இப்போ இதை செஞ்சு பாருங்க
- ரெண்டு numbers கேட்டு வகுங்க; number இல்லாததையும், zero-ஆல வகுக்கிறதையும் தெளிவான messages-ஓட கையாளுங்க.
- Square brackets வெச்சு dictionary-ல ஒரு பேரை தேடுங்க;
KeyError-ஐ பிடிச்சு "Not found" print பண்ணுங்க.
Create a free account to save your progress, or sign in.