오류 발생시 다음 루프 값으로 tryCatch 건너 뛰기를 사용 하시겠습니까?
나는 tryCatch
문서뿐만 아니라 커진 에 대한 몇 가지 다른 질문을 읽었습니다 .
그래도 이해가 안 돼요
루프를 실행 중이며 next
몇 가지 오류가 발생하면 건너 뛰고 싶습니다 .
for (i in 1:39487) {
# EXCEPTION HANDLING
this.could.go.wrong <- tryCatch(
attemptsomething(),
error=function(e) next
)
so.could.this <- tryCatch(
doesthisfail(),
error=function(e) next
)
catch.all.errors <- function() { this.could.go.wrong; so.could.this; }
catch.all.errors;
#REAL WORK
useful(i); fun(i); good(i);
} #end for
(참고로 next
찾을 수있는 문서가 없습니다 )
내가 이것을 실행하면 R
경적 :
Error in value[[3L]](cond) : no loop for break/next, jumping to top level
여기서 내가 놓친 기본 포인트는 무엇입니까? tryCatch
의가 내 명확하다 for
루프, 왜하지 않습니다 R
알고?
사용의 열쇠 tryCatch
는 그것이 객체를 반환한다는 것을 깨닫는 것입니다. 내부에 오류가 있으면 tryCatch
이 객체는 class에서 상속 error
합니다. 함수를 사용하여 클래스 상속을 테스트 할 수 있습니다 inherit
.
x <- tryCatch(stop("Error"), error = function(e) e)
class(x)
"simpleError" "error" "condition"
편집하다:
논쟁의 의미는 무엇입니까 error = function(e) e
? 이것은 나를 당혹스럽게했고 문서에 잘 설명되어 있지 않다고 생각합니다. 무슨 일이 일어나고 있는지이 인수는 당신이하려는 표현에서 발생하는 오류 메시지를 포착 tryCatch
합니다. 오류가 발견되면 값으로 반환됩니다 tryCatch
. 도움말 문서에서 이것은 calling handler
. e
내부 의 인수 error=function(e)
는 코드에서 발생하는 오류 메시지입니다.
저는 사용 next
이 나쁜 일이었던 오래된 절차 적 프로그래밍 학교에서 왔습니다 . 그래서 나는 당신의 코드를 다음과 같이 다시 작성할 것입니다. ( next
내에서 문을 제거 했습니다 tryCatch
.) :
for (i in 1:39487) {
#ERROR HANDLING
possibleError <- tryCatch(
thing(),
error=function(e) e
)
if(!inherits(possibleError, "error")){
#REAL WORK
useful(i); fun(i); good(i);
}
} #end for
함수 next
는 ?
for` 안에 문서화되어 있습니다.
기본 작업 루틴을 내부에 두는 대신이를 사용하려면 if
코드가 다음과 같아야합니다.
for (i in 1:39487) {
#ERROR HANDLING
possibleError <- tryCatch(
thing(),
error=function(e) e
)
if(inherits(possibleError, "error")) next
#REAL WORK
useful(i); fun(i); good(i);
} #end for
rm(list=ls())
for (i in -3:3) {
#ERROR HANDLING
possibleError <- tryCatch({
print(paste("Start Loop ", i ,sep=""))
if(i==0){
stop()
}
}
,
error=function(e) {
e
print(paste("Oops! --> Error in Loop ",i,sep = ""))
}
)
if(inherits(possibleError, "error")) next
print(paste(" End Loop ",i,sep = ""))
}
내가 본 유일한 자세한 설명은 http://mazamascience.com/WorkingWithData/?p=912 에서 찾을 수 있습니다 .
다음은 tryCatch의 작동 방식을 보여주는 해당 블로그 게시물의 코드 클립입니다.
#!/usr/bin/env Rscript
# tryCatch.r -- experiments with tryCatch
# Get any arguments
arguments <- commandArgs(trailingOnly=TRUE)
a <- arguments[1]
# Define a division function that can issue warnings and errors
myDivide <- function(d, a) {
if (a == 'warning') {
return_value <- 'myDivide warning result'
warning("myDivide warning message")
} else if (a == 'error') {
return_value <- 'myDivide error result'
stop("myDivide error message")
} else {
return_value = d / as.numeric(a)
}
return(return_value)
}
# Evalute the desired series of expressions inside of tryCatch
result <- tryCatch({
b <- 2
c <- b^2
d <- c+2
if (a == 'suppress-warnings') {
e <- suppressWarnings(myDivide(d,a))
} else {
e <- myDivide(d,a) # 6/a
}
f <- e + 100
}, warning = function(war) {
# warning handler picks up where error was generated
print(paste("MY_WARNING: ",war))
b <- "changing 'b' inside the warning handler has no effect"
e <- myDivide(d,0.1) # =60
f <- e + 100
return(f)
}, error = function(err) {
# warning handler picks up where error was generated
print(paste("MY_ERROR: ",err))
b <- "changing 'b' inside the error handler has no effect"
e <- myDivide(d,0.01) # =600
f <- e + 100
return(f)
}, finally = {
print(paste("a =",a))
print(paste("b =",b))
print(paste("c =",c))
print(paste("d =",d))
# NOTE: Finally is evaluated in the context of of the inital
# NOTE: tryCatch block and 'e' will not exist if a warning
# NOTE: or error occurred.
#print(paste("e =",e))
}) # END tryCatch
print(paste("result =",result))
R에서 for 루프 내에서 함수를 실행할 때 for 루프에서 벗어나는 한 가지 누락 은 다음과 같습니다.
next
함수 내에서 작동하지 않습니다.- You need to send some signal or flag (e.g.,
Voldemort = TRUE
) from inside your function (in my casetryCatch
) to the outside. - (this is like modifying a global, public variable inside a local, private function)
- Then outside the function, you check to see if the flag was waved (does
Voldemort == TRUE
). If so you callbreak
ornext
outside the function.
I found other answers very confusing. Here is an extremely simple implementation for anyone who wants to simply skip to the next loop iteration in the event of an error
for (i in 1:10) {
skip_to_next <- FALSE
# Note that print(b) fails since b doesn't exist
tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
참고URL : https://stackoverflow.com/questions/8093914/use-trycatch-skip-to-next-value-of-loop-upon-error
'UFO ET IT' 카테고리의 다른 글
PHP의 타임 스탬프에서 DateTime 만들기 <5.3 (0) | 2020.12.12 |
---|---|
Windows Forms 응용 프로그램에서 스플래시 화면을 구축하는 방법은 무엇입니까? (0) | 2020.12.12 |
많은 프로그래밍 언어에서 문자열을 변경할 수없는 이유는 무엇입니까? (0) | 2020.12.12 |
H.264 비디오와 MPEG-4 비디오의 차이점은 무엇입니까? (0) | 2020.12.12 |
V8 JavaScript (Chrome 및 Node.js)에서 줄 번호에 액세스 (0) | 2020.12.12 |