嘗試下面的代碼後,我終於明白了這一點。
def get_age():
age = input("Please enter your age: ")
if not age.isdigit():
my_error = TypeError("{0} is not integer".format(age))
raise my_error
elif age < 0:
# Create a new instance of an exception
my_error = ValueError("{0} is not positive".format(age))
raise my_error
return age
def a():
get_age()
def b():
a()
def c():
b()
def d():
try:
c()
print("haha")
except ValueError:
print("no one has negative age, you fool")
#except TypeError:
#print("you should input an integer, dear")
d()
以下是我未處理TypeError時的錯誤消息。
RESTART: the_path_to_my_python_file.py
Please enter your age: th
Traceback (most recent call last):
File "the_path_to_my_python_file.py", line 33, in <module>
d()
File "the_path_to_my_python_file.py", line 26, in d
c()
File "the_path_to_my_python_file.py", line 22, in c
b()
File "the_path_to_my_python_file.py", line 18, in b
a()
File "the_path_to_my_python_file.py", line 14, in a
get_age()
File "the_path_to_my_python_file.py", line 5, in get_age
raise my_error
TypeError: th is not integer
你看到它不會告訴你「in module」了。每次它都會告訴您發生錯誤的函數的名稱。我認爲這是「模塊」中提供的那種信息。
在文件中編寫代碼並直接在控制檯「python script.py」中運行它,然後您將看到文件名而不是「」。如果代碼是從其他文件導入的,那麼您會看到此模塊名稱,而不是'' –
furas
是的。我試過了,我得到了你想說的話。雖然這與「在」中無關,對吧?或者我真的不應該擔心這個廢話。 –
study
只有在Python Shell中運行時纔會看到'','' - 因爲Shell不會從文件讀取代碼。通常它顯示文件名和模塊名稱,當代碼在許多文件和模塊中時它是有用的。 –
furas