Unusual Code behavior

Hello,
When the code is run on local machine results are getting as expected but when trying to run the same code through server, the code is breaking randomly.(Sometimes results are as expected but in next successive runs exception is thrown as shown in the attached image)
Can anyone please help with issue mentioned.

Regards,
Bhavita