Python Try Except

try 块允许您测试代码块以查找错误。

except 块允许您处理错误。

finally 块允许您执行代码,无论 try 和 except 块的结果如何。

异常处理

当我们调用 Python 并发生错误或异常时,通常会停止并生成错误消息。

可以使用 try 语句处理这些异常:

Example

try 块将生成异常,因为 x 未定义:

try:
  print(x)
except:
  print("An exception occurred")

အကြောင်းကျည်း အချက်အလက်

由于 try 块引发错误,因此会执行 except 块。

如果没有 try 块,程序将崩溃并引发错误:

Example

该语句将引发错误,因为未定义 x:

print(x)

အကြောင်းကျည်း အချက်အလက်

多个异常

您可以根据需要定义任意数量的 exception 块,例如,假如您要为特殊类型的错误执行特殊代码块:

Example

如果 try 块引发 NameError,则打印一条消息,如果是其他错误则打印另一条消息:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

အကြောင်းကျည်း အချက်အလက်

Else

如果没有引发错误,那么您可以使用 else 关键字来定义要执行的代码块:

Example

在本例中,try 块不会生成任何错误:

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

အကြောင်းကျည်း အချက်အလက်

Finally

如果指定了 finally 块,则无论 try 块是否引发错误,都会执行 finally 块。

Example

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

အကြောင်းကျည်း အချက်အလက်

This is very useful for closing objects and cleaning up resources:

Example

Try to open and write to an unwritable file:

try:
  f = open("demofile.txt")
  f.write("Lorum Ipsum")
except:
  print("Something went wrong when writing to the file")
finally:
  f.close()

အကြောင်းကျည်း အချက်အလက်

The program can continue, and the file object will not be opened.

Raising an exception

As a Python developer, you can choose to raise an exception when a condition occurs.

To raise (throw) an exception, use raise Keywords.

Example

If x is less than 0, then raise an exception and terminate the program:

x = -1
if x < 0:
  raise Exception("Sorry, no numbers below zero")

အကြောင်းကျည်း အချက်အလက်

raise Keywords are used to raise exceptions.

You can define the type of the exception you want to raise, as well as the text printed to the user.

Example

If x is not an integer, then raise TypeError:

x = "hello"
if not type(x) is int:
  raise TypeError("Only integers are allowed")

အကြောင်းကျည်း အချက်အလက်