handle exceptions in python

In Python, exceptions are errors that occur during program execution. To handle exceptions in Python, we use a try-except block.

The try block contains the code that might raise an exception, and the except block contains the code to handle the exception. In the except block, we can specify the type of exception that we want to catch.

For example, let's say we want to read a file that doesn't exist. If we try to open the file using the open() function, we will get a FileNotFoundError. We can handle this exception using the following try-except block:

main.py
try:
    file = open("myfile.txt", "r")
except FileNotFoundError:
    print("File not found.")
95 chars
5 lines

In this example, if the file "myfile.txt" is not found, the except block will be executed and the message "File not found." will be printed.

We can also raise our own exceptions using the raise keyword. For example, if we want to check if a variable is an integer, we can raise a ValueError if it is not:

main.py
def check_int(num):
    if not isinstance(num, int):
        raise ValueError("Not an integer.")
    else:
        print("Number is an integer.")
146 chars
6 lines

In this example, the check_int() function raises a ValueError if the variable num is not an integer.

Finally, we can use a finally block to execute code after the try and except blocks, regardless of whether an exception was raised or not. This block is useful for cleaning up resources that were used in the try block:

main.py
try:
    file = open("myfile.txt", "r")
    # code to read the file
except FileNotFoundError:
    print("File not found.")
finally:
    file.close()
149 chars
8 lines

In this example, the file.close() statement is executed regardless of whether an exception was raised or not. This ensures that the file is properly closed, even if an error occurred while reading it.

gistlibby LogSnag