Kuskuren Gudanarwa da Keɓancewa a ciki Python

A cikin Python, sarrafa kurakurai da keɓantawa muhimmin sashi ne na tsarin shirye-shirye. Lokacin gudanar da shirin, kurakurai da keɓancewa na iya faruwa. Gudanar da kurakurai da keɓantawa yana ba shirin damar ɗauka da ba da rahoton waɗannan yanayi na bazata cikin sassauƙa kuma a cikin hanyar karantawa.

 

Magance Kurakurai gama gari( Exception Handling)

A cikin Python, muna amfani da try-except toshe don magance kurakuran gama gari. Tsarin try-except yana ba da damar shirin aiwatar da toshe lambar a cikin try sashin, kuma idan kuskure ya faru a cikin wannan toshe, shirin zai matsa zuwa except sashin don magance wannan kuskuren.

Misali:

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

 

Gudanar da Gabaɗaya keɓancewa

Baya ga sarrafa takamaiman nau'ikan kurakurai, za mu iya amfani da su except ba tare da fayyace takamaiman nau'in kuskure ba. Wannan yana taimaka wa keɓanta gabaɗaya waɗanda ba mu sani ba tukuna.

Misali:

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

 

Gudanar da Nau'o'in Banbancin Maɗaukaki da yawa

Hakanan zamu iya ɗaukar nau'ikan kurakurai daban-daban a cikin try-except toshe iri ɗaya ta amfani da except jumla mai yawa.

Misali:

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.")  

 

A else da finally Clauses

  • Sashen else yana ba da damar aiwatar da toshe na lamba lokacin da babu kuskure a cikin try sashin.
  • Salon finally yana ba da damar aiwatar da toshe lambar bayan an kammala duka try da sassan biyu. except

Misali:

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.")  

 

Gudanar da kurakurai da keɓantacce a cikin Python yana sa shirin ya fi ƙarfi kuma yana ƙara kwanciyar hankali. Lokacin sarrafa kurakurai da kyau, za mu iya samar da saƙon da suka dace ko aiwatar da ayyuka daidai lokacin da al'amuran da ba zato ba tsammani suka faru.