try, except, finally
In python, error handling is done using try, except, and optionally finally blocks. This allows controlling the flow of the program when an exception (error) occurs and prevents the program from abruptly stopping.
Catching Exceptions
Section titled “Catching Exceptions”These examples show how to handle a specific error, in this case a division by zero, using try and except. If an error occurs within the try block, the except block executes to handle it safely without stopping the program.
try: result = 10 / 0except ZeroDivisionError: print("Error: you can't divide by zero.")
Catching Multiple Exceptions
Section titled “Catching Multiple Exceptions”This example catches more than one type of exception. It tries to convert a non-numeric string to an integer, which raises a ValueError. Additionally, it anticipates a TypeError if a different type of error occurs. This allows handling multiple possible errors separately and clearly.
try: number = int("abc")except ValueError: print("Error: can't convert text to number.")except TypeError: print("Error: Invalid data type.")
Using finally
Section titled “Using finally”The finally block always executes regardless of whether an exception occurred or not. In this case, an attempt is made to open a non-existent file. If a FileNotFoundError occurs, it is handled, and then the finally block executes to indicate that the attempt has finished, which is useful for releasing resources or logging actions.
try: file = open("non-existent.txt", "r") content = file.read()except FileNotFoundError: print("Error: file not found.")finally: print("Finishing reading attempt.")