Try blocks in R for error handling

R scripts halt execution when an error is encountered.  When batch processing this produces situations where the error can not be merely skipped like it could in a .net application with  user involvement. To use Try() blocks for error handling in R, enclose the entire block of code in a try() block.

try({
# MACD and SIGNAL
png(filename=args[3], width=900, height=300)
print('MACD and Signal ')
g_range2 <- range(data_points$MACD, data_points$SIGNAL)
plot(data_points$MACD, type="o", col=plot_colors[1],  ylim=g_range2, axes=TRUE,
 ann=FALSE, panel.first=grid(), lty="dotted")
lines(data_points$SIGNAL, type="o", pch=23, lty="solid", col=plot_colors[6])
title(main=args[9], col.main="Black", font.main=4)
legend("topleft", legend=c("Signal", "MACD"), col=c("black", "blue"), lty=1:3, cex=0.8)
title(xlab= "Days", col.lab=rgb(0,0.5,0))
title(ylab= "MACD and Signal", col.lab=rgb(0,0.5,0))
dev.off()
})

Leave a Reply