UFO ET IT

오류 발생시 다음 루프 값으로 tryCatch 건너 뛰기를 사용 하시겠습니까?

ufoet 2020. 12. 12. 11:54
반응형

오류 발생시 다음 루프 값으로 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 case tryCatch) 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 call break or next 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

반응형