stop()으로 오류 발생시키기
Coddy R 여정의 논리와 흐름 섹션에 포함된 레슨. 64개 중 52번째.
stop("message")는 오류를 발생시킵니다. 함수가 즉시 중지되고, 그 이후의 어떤 코드도 실행되지 않으며, R은 메시지를 출력합니다. 함수가 처리할 수 없는 입력을 받을 때 사용하세요.
check_qty <- function(q) {
if (q <= 0) stop("quantity must be positive")
q
}
print(check_qty(3))
print(check_qty(-1))
print("never printed")출력:
[1] 3
Error in check_qty(-1) : quantity must be positive
Calls: print -> check_qty
Execution halted오류 텍스트에는 실패한 호출이 표시되며, Execution halted는 전체 스크립트가 중지되었음을 의미합니다. 마지막 print()는 실행되지 않았습니다. 오류는 일반 출력이 아니라 오류 스트림에 기록되므로 Coddy에서는 오류나 경고가 하나라도 출력되면 테스트가 실패합니다.
stopifnot()는 여러 조건을 한 번에 확인하며, 그중 FALSE인 첫 번째 조건에 대해 오류를 발생시킵니다. 이름이 지정된 조건은 해당 이름을 메시지로 사용합니다.
area <- function(w, h) {
stopifnot("width must be positive" = w > 0, "height must be positive" = h > 0)
w * h
}
print(area(2, 3))
print(area(2, -1))출력:
[1] 6
Error in area(2, -1) : height must be positive
Calls: print -> area -> stopifnot
Execution haltedpaste0() 또는 sprintf()를 사용하여 값으로 메시지를 구성하면, 독자가 무엇이 잘못되었는지 확인할 수 있습니다:
get_item <- function(items, i) {
if (i > length(items)) stop(sprintf("index %d is past the end (%d items)", i, length(items)))
items[i]
}
print(get_item(c("a", "b"), 5))출력:
Error in get_item(c("a", "b"), 5) : index 5 is past the end (2 items)
Calls: print -> get_item
Execution halted작업을 수행하기 전에 함수 시작 부분에서 오류를 발생시키세요. 일찍 중단하는 검사를 사용하면 나머지 함수는 유효한 입력이라고 가정할 수 있으므로 단순하게 유지할 수 있습니다:
withdraw <- function(balance, amount) {
if (amount <= 0) stop("amount must be positive")
if (amount > balance) stop("insufficient funds")
balance - amount
}챌린지
쉬움make_order(item, qty, stock)을 완성하세요. stop()을 사용하여 오류를 발생시키세요:
qty가 1보다 작을 때quantity must be at least 1qty가stock보다 클 때only <stock> left를 사용하세요. 예:only 3 left
그렇지 않으면 ordered <qty> x <item>을 반환하세요.
제공된 코드는 item, quantity, stock을 읽고, 여러분의 함수를 호출한 다음 그 결과 또는 오류 메시지 앞에 Error: 를 붙인 값을 출력하므로, 어떤 테스트에서도 R 자체의 오류 텍스트가 표시되지 않습니다.
직접 해보기
make_order <- function(item, qty, stock) {
# 여기에 코드를 작성하세요
""
}
# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
result <- tryCatch(make_order(input[1], as.numeric(input[2]), as.numeric(input[3])),
error = function(e) paste("Error:", conditionMessage(e)))
cat(result, sep = "\n")
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러