Penanganan Kesalahan lan Pangecualian ing Python

Ing Python, nangani kasalahan lan pangecualian minangka bagéyan penting saka proses program. Nalika mbukak program, kesalahan lan pangecualian sing ora dikarepake bisa kedadeyan. Nangani kesalahan lan pangecualian ngidini program kanggo nangani lan nglaporake kahanan sing ora dikarepke iki kanthi fleksibel lan bisa diwaca.

 

Nangani Kesalahan Umum( Exception Handling)

Ing Python, kita nggunakake try-except pemblokiran kanggo nangani kasalahan umum. Struktur kasebut try-except ngidini program nglakokake blok kode ing try bagean kasebut, lan yen ana kesalahan ing blok iki, program bakal pindhah menyang except bagean kasebut kanggo nangani kesalahan kasebut.

Tuladha:

try:  
    # Attempt to perform an invalid division  
    result = 10 / 0  
except ZeroDivisionError:  
    print("Error: Cannot divide by zero.")  

 

Nangani Pengecualian Umum

Saliyane nangani jinis kesalahan tartamtu, kita uga bisa nggunakake except tanpa nemtokake jinis kesalahan tartamtu. Iki mbantu nangani pengecualian umum sing ora dingerteni sadurunge.

Tuladha:

try:  
    # Attempt to perform an invalid division  
    result = 10 / 0  
except:  
    print("An error occurred.")  

 

Nangani Multiple Jinis Pangecualian

Kita uga bisa ngatasi macem-macem jinis kesalahan ing try-except blok sing padha kanthi nggunakake pirang-pirang except klausa.

Tuladha:

try:  
    # Attempt to open a non-existent file  
    file = open("myfile.txt", "r")  
    content = file.read()  
except FileNotFoundError:  
    print("Error: File not found.")  
except PermissionError:  
    print("Error: No permission to access the file.")  

 

The else lan finally Klausa

  • Klausa kasebut else ngidini nglakokake blok kode nalika ora ana kesalahan ing try bagean kasebut.
  • Klausa kasebut finally ngidini ngeksekusi blok kode sawise loro try lan except bagean rampung.

Tuladha:

try:  
    num = int(input("Enter an integer: "))  
except ValueError:  
    print("Error: Not an integer.")  
else:  
    print("The number you entered is:", num)  
finally:  
    print("Program ends.")  

 

Nangani kesalahan lan pangecualian ing Python ndadekake program luwih mantep lan nambah stabilitas. Nalika nangani kesalahan kanthi bener, kita bisa menehi pesen sing cocog utawa nindakake tumindak sing cocog nalika ana kahanan sing ora dikarepake.