I am closing the device (here: pdf() ) I am plotting to at the end of my function with dev.off(). However, if the function/loop terminates due to an error the device stays open. When a function gets repeatedly called, this can lead to quite a lot of open devices; and file handles.
How can I make sure the device gets closed even if the function fails?
I do remember that I once saw how to do this, but I cannot remember.
Error Code 43 can be caused by hardware problems or driver or settings corruption. To address this issue, we recommend performing a clean install of latest graphics drivers provided by the system manufacturer since these drivers are customized.
Sometimes you may see this error message: Windows has stopped this device because it has reported problems (Code 43). This usually means that the driver (which does NOT come from Seagate; this driver comes from Windows) has lost communication with the drive or the driver has crashed.
on.exit()
is made for situations just like this. It's good practice to use it whenever opening a (file or other) connection in a non-interactive setting.
f <- function() {
pdf(tempfile()) # tempfile() so example doesn't clutter up working directory.
on.exit(dev.off())
plot(randomNonExistentObjectName)
}
f()
# Error in plot(randomNonExistentObjectName) :
# object 'randomNonExistentObjectName' not found
dev.list()
# NULL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With