了解 "try" 和 "except" python
understanding "try" and "except" python
据我所知,到目前为止,计算机将尝试 运行 try 部分中的代码,并将排除 except 部分中提到的内容。一旦计算机收到 except 中提到的内容,它就会 运行 除了代码。
所以,我尝试了以下方法:
try:
if year // 100:
print year, "is not a leap year"
else:
print year, "is not a leap year"
except year // 400 and year // 4:
print "is a leap year"
这行不通。
我想知道为什么会这样?
基本上 try and except 就像 if 和 else...有点
除非你 try
如果它没有引发异常它会执行 try
代码块但是当它失败时它将执行 except
块例如
a = [1,2,3,4,"hello"]
for i in a:
try:
print(i)
i + 1
except:
print("nope " + i + " is a string")
请阅读the doc。
The try
statement works as follows.
- First, the try clause (the statement(s) between the
try
and except
keywords) is executed.
- If no exception occurs, the except clause is skipped and execution of the
try
statement is finished.
- If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception
named after the except keyword, the except clause is executed, and
then execution continues after the
try
statement.
- If an exception occurs which does not match the exception named in the except clause, it is passed on to outer
try
statements; if no
handler is found, it is an unhandled exception and execution stops
with a message as shown above.
据我所知,到目前为止,计算机将尝试 运行 try 部分中的代码,并将排除 except 部分中提到的内容。一旦计算机收到 except 中提到的内容,它就会 运行 除了代码。
所以,我尝试了以下方法:
try:
if year // 100:
print year, "is not a leap year"
else:
print year, "is not a leap year"
except year // 400 and year // 4:
print "is a leap year"
这行不通。
我想知道为什么会这样?
基本上 try and except 就像 if 和 else...有点
除非你 try
如果它没有引发异常它会执行 try
代码块但是当它失败时它将执行 except
块例如
a = [1,2,3,4,"hello"]
for i in a:
try:
print(i)
i + 1
except:
print("nope " + i + " is a string")
请阅读the doc。
The
try
statement works as follows.
- First, the try clause (the statement(s) between the
try
andexcept
keywords) is executed.- If no exception occurs, the except clause is skipped and execution of the
try
statement is finished.- If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the
try
statement.- If an exception occurs which does not match the exception named in the except clause, it is passed on to outer
try
statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.