R 避免留下使用过的设备

R 避免留下使用过的设备,r,error-handling,pdf-generation,R,Error Handling,Pdf Generation,我想通过函数在pdf上书写 pdf("termolayout.pdf") generate_termolayout(db) #This functions prints thermolayouts, but when the db is corrupted, generates errors dev.off() 如何确保R运行dev.off()即使generate\u termolayout失败? mypdf <- function() { pdf("termolayout.

我想通过函数在pdf上书写

pdf("termolayout.pdf")
generate_termolayout(db) 
   #This functions prints thermolayouts, but when the db is corrupted, generates errors
dev.off()

如何确保R运行
dev.off()
即使
generate\u termolayout
失败?

mypdf <- function() {
  pdf("termolayout.pdf")
  on.exit(dev.off())
  stop("An error.")
}

mypdf()
#Error in mypdf() : An error.
dev.cur()
#RStudioGD 
#2 

mypdf使用
on.exit

mypdf <- function() {
  pdf("termolayout.pdf")
  on.exit(dev.off())
  stop("An error.")
}

mypdf()
#Error in mypdf() : An error.
dev.cur()
#RStudioGD 
#2 
mypdf查看
tryCatch()
查看
tryCatch()