32. PYTHON (Exception & File) – Finally

Belajar Bahasa Python Lengkap

Blok kode pada statement finally akan tetap diekekusi walaupun terjadi error pada blok try/except. Lihat pada contoh kode di bawah ini:

try:
	bagi = 8 / 0

	print(bagi)

except ZeroDivisionError:
	print("error: pembagian nol")

finally:
	print("Blok finally tetap dieksekusi")
=====>
error: pembagian nol
Blok finally tetap dieksekusi
=====>

Walaupun di dalam blok kode except juga terjadi error, blok finally akan tetap dieksekusi.

try:
	print("angka 1")
	print(8/0)

except ZeroDivisionError:
	print(sebuah_variabel)

finally:
	print("Blok finally tetap dieksekusi")
=====>
angka 1
Blok finally tetap dieksekusi

ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

NameError: name 'sebuah_variabel' is not defined
=====>

LANJUTKAN BACA MATERI LENGKAP


Leave a Reply

Your email address will not be published. Required fields are marked *

two × 3 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.