Python Try and Except Error Handling

In this script, we will see how we can implement error handling in python scripting. We will use the try and except method. Sometimes if there is an error in the script or in the remote device where you are trying to connect then the script will break and stop working. According to a 2026 guide by GeeksforGeeks on Python exception handling, exception handling allows a program to handle unexpected runtime errors—such as invalid input, connection timeouts, and type mismatches—in a controlled way instead of crashing abruptly.

Error handling using the try-and-except method deals with these kinds of situations. If you are using any particular python library, then check the documentation to see available exception errors.

Python Try and Except Error Handling

Python Try and Except Error Handling

Below is the script which we have used for error handling. Check out the link for email sending script in python. Full tutorial for python scripting for videos for storage admin.

import paramiko
p = paramiko.SSHClient()
cred = open("cred.csv","r")
for i in cred.readlines():
    try:
        line=i.strip()
        ls =line.split(",")
        p.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        p.connect("%s"%ls[0],port =22, username = "%s"%ls[1], password="%s"%ls[2])
        stdin, stdout, stderr = p.exec_command("uname -a")
        opt = stdout.readlines()
        opt ="".join(opt)
        temp=open("%s.txt"%ls[0],"w")
        temp.write(opt)
        temp.close()
    except Exception as error:
        print(error)
cred.close()

Best Practices for Exception Handling

When writing production-grade scripts, relying solely on a broad except Exception as error: block can sometimes mask underlying issues or make debugging difficult. To write more resilient code, consider the following best practices:

  • Catch Specific Exceptions: Instead of catching all exceptions universally, target specific errors like paramiko.AuthenticationException or socket.timeout so you know exactly what went wrong.
  • Use Finally Blocks: Utilize a finally block to ensure that resources—such as open file handles, database connections, or SSH sessions—are properly closed regardless of whether an error occurred.
  • Log Errors Properly: Rather than just printing errors to the console, use Python’s built-in logging module to record timestamps and error levels, which greatly aids in auditing and troubleshooting automation tasks.

Watch the video for a full explanation and subscribe to the channel for more such videos.

Frequently Asked Questions (FAQ)

What is the purpose of try and except in Python?

The try and except blocks are used to catch and handle runtime exceptions in Python. The code that might cause an error is placed in the try block, while the code to handle the error if it occurs is placed in the except block, preventing the program from crashing abruptly.

Why is error handling important in network automation scripts?

When connecting to multiple remote devices (such as via SSH using Paramiko), issues like connection timeouts, incorrect credentials, or unreachable hosts can occur. Error handling ensures that if one device fails, the script catches the exception and continues running for the remaining devices.

Should I use a generic ‘Exception’ catch block?

While catching a generic Exception is helpful for logging unexpected errors as shown in the script, it is often a best practice in production environments to catch specific exceptions (like paramiko.AuthenticationException or socket.timeout) to handle different error scenarios uniquely.

Conclusion

The given example is simple, you can use this method in various scenarios to catch errors and save them into a log file for further checks. While using this method, the script will continue to run, even if the errors are critical.