Anahtar Kelime hariç Python
Örnek
İfade bir hata verirse "Bir şeyler ters gitti" yazdırın:
try:
x > 3
except:
print("Something went wrong")
Tanım ve Kullanım
Anahtar except
sözcük, bloklar hariç try...'da kullanılır. Try bloğu bir hata verirse çalıştırılacak bir kod bloğu tanımlar.
Farklı hata türleri için farklı bloklar ve hiçbir şey ters gitmediğinde yürütülecek bloklar tanımlayabilirsiniz, aşağıdaki örneklere bakın.
Daha fazla örnek
Örnek
NameError ise bir mesaj, TypeError ise başka bir mesaj yazın:
x = "hello"
try:
x > 3
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
Örnek
Bir hata oluşturan, ancak tanımlanan hata türlerinden hiçbiri (bu durumda bir ZeroDivisionError) olmayan bir ifade yürütmeyi deneyin:
try:
x = 1/0
except NameError:
print("You have a
variable that is not defined.")
except TypeError:
print("You
are comparing values of different type")
except:
print("Something else went wrong")
Örnek
Herhangi bir hata oluşmadıysa bir mesaj yazın:
x = 1
try:
x > 10
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
else:
print("The 'Try' code was executed without raising any errors!")
İlgili Sayfalar
Anahtar try
kelime.
Anahtar finally
kelime.