Running the same code on server and desktop – Exception/Error handling

Recently, I was bogged with a problem where I had a code running on the server which moves files after execution of the entire process from one folder into another. This created a dilemma for me if I should create the same folder paths on my desktop to keep the code running or to bear with the errors that python threw back at me when I was running it on desktop.

Then after a lot of research I came across the beautiful world of Exception and Error Handling in Python. This triggered an idea to implement the same for execution based on environment.

Error handling protects your program against potential failures that would otherwise cause your program to exit in an uncontrolled fashion.

  • try a block of code with a probability that error will occur. Here I put my sever code. Like moving a file from one folder to another. This was bound to fail on my desktop as no such folders existed.
  • except block lets you handle the error. This portion of the code will execute if error occurs due to above code block execution. This portion cannot be empty. I put in a print(“hello”) here to avoid the error. I think you can probably avoid all the remaining parts of the code if your problem was just to do something in a particular environment (like on server – in my case), and just move on if that was not the case (i.e. on desktop) in case of failure
  • else block if no exception in the program. i.e. do this if no error happens
  • finally regardless of the result of the try- and except blocks, this code always execute.

With this we are letting Python know that we are aware of the error and this is how you should handle it. Thus, error handling in python can be easily crafted to tackle different execution environments

As you can clearly see, the above structure gives you immense control over all possible conditions that could happen. In my case it was just to try a file move within server folders in case the execution in on server, else just move on without error.

For those curious on the code I used:

try:
# Some action that could raise an error..This is server code
newPath = shutil.copy(‘file1.json’, ‘/home/ubuntu/folderz’)
newPath = shutil.copy(‘ file2 .png’, ‘/home/ubuntu/ folderz ‘)
newPath = shutil.copy(‘ file3 .png’, ‘/home/ubuntu/ folderz ‘)

except:
# What to do when an error occurs
print(“not server…dont copy”)

As you can see I kept it very simple. I only retained what I need. In this post, we discussed about a particular type of situation where try could be used.

There are other type of errors where you can try this out.

  • Syntax Error
  • Out of Memory Error
  • Recursion Error

Leave a comment

Design a site like this with WordPress.com
Get started