Skip to main content

Exception

Exception例外處理

  • 有時候會產生預期以外的結果,餓時可以使用例外處理來解決
  • 可以使用try/except語法
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")

###########################################################
def division(a,b):
try:
return a/b
except as e:
print(e)
print(division(3,0))

Raise Exception產生例外

  • 執行程式時可以依照判定來產生例外
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")