Handling errors using try-except blocks python

Handling errors using try-except blocks python

Managing program errors while working with files in Python file handling is simplified by using the try-except block, as the try-except block helps you manage common problems that arise during file handling operations. Use the try-except block for error management while reading and writing from existing files in file handling.

Handling errors using try-except blocks python

Reading from Python File.

When reading data from a file in file handling, common problems include FileNotFoundError (if the file doesn’t exist), PermissionError (if you don’t have permission to access the file), or IOError (for general input/output problems). So let’s manage these errors properly.

file_location = ‘sample.txt’

try:

    with open(file_location, ‘r’) as file:

        for line in file:

            print(line.strip())  # stip function to read each line in file

except FileNotFoundError:

    print(f”Error – it display the ‘{file_location}’ file you want not available”)

except PermissionError:

    print(f”Error – file access permission deny ‘{file_location}’.”)

except IOError as e:

    print(f”Error – file disk io error generate {e}”)

except Exception as e:

    print(f”Error – An unexpected error generate {e}”)

in the try-except block example above.

Here the try block provides options to open the sample.txt file and read the file.

In specific exceptions (FileNotFoundError, PermissionError, IOError) different try except blocks are found out, you can manually manage these different program errors in different ways depending upon their type.

Exception block finds out unexpected error in any programming,

writing to python file.

In Python file handling operation, while writing to file, different errors can be added to the file like FilePermissionError (if you have no permission to write to the file) or File IOError (for general input/output error). So let’s know how to manage errors in Python file program.

file_location = ‘display.txt’

try:

    with open(file_location, ‘w’) as file: # open file for write operation

        file.write(“write first line in display.txt file\n”) # write text or line in display.txt file

        file.write(“write second line in display.txt file”)

except PermissionError:

    print(f”Error – restrict permission into the file ‘{file_location}’.”)

except IOError as e:

    print(f”Error – file disk io error generate {e}”)

except Exception as e:

    print(f”Error – An suddenly unexpected error generated {e}”)

In the above example, the try block opens the display.txt file in write mode (‘w’), and writes a two-line sentence into it.

Whereas in different file try except block error PermissionError and IOError are managed in separate except block so that if any problem occurs in file writing operation then it can be easily managed or handled.

Appending text/info to Python file.

While appending text or information to a file in Python file handling process, general file run errors of type (PermissionError, IOError) may be displayed. So let us manage these errors in file append mode.

try:

with open(file_location, ‘a’) as file: # open append.txt file for appending mode operation

file.write(“let append desire content in this mode\n”)

except PermissionError:

print(f”Error – it restrict to append in file ‘{file_location}’.”)

except IOError as e:

print(f”Error- io disk error generated when file data append {e}}”)

except Exception as e:

print(f”Error – unwanted file append error generated {e}”)

Here try block allows you to open display.txt file in append mode (‘a’) and append desired content to it.

In case of specific program error (PermissionError, IOError) file handling operation is managed separately in except block.

Handling multiple errors in file handling.

If you want, you can manage multiple file handling program errors in a single try block, it depends on how you want to manage multiple error conditions.

try:

    with open(file_location, ‘r’) as file: # open file for read operation

        for line in file:

            print(line.strip())  # strip function used to access file line

except (FileNotFoundError, PermissionError) as e:

    print(f”Error – file error {e}”)

except IOError as e:

    print(f”Error: file storage io disk error generate {e}”)

except Exception as e:

    print(f”Error – unwanted file error generate {e}”)

Here in file handling program, FileNotFoundError and PermissionError are being managed with a single try except block, in this program you can clearly understand, how to manage multiple file handling error programs in a single program.