Solution Review: Try Catch
In this review, we provide a detailed analysis of the solution to this problem.
We'll cover the following
Solution: Try Catch Block
calculateLog <- function(test){tryCatch({cat(log(test))},error = function(e){cat("This operation is not allowed!")},warning = function(w){cat("This operation is not allowed!")})}# Driver CodecalculateLog(10)cat("\n")calculateLog(-10)cat("\n")calculateLog("a")cat("\n")
Explanation
We use
log()
to calculate the log of a variable or constant.
Here, log(test)
is the function call which may throw an exception, therefore we have used tryCatch()
to handle errors and warnings.
We have to write both the error and warning functions because for negative numbers the log()
function throws a warning and for non-integers, it throws an error.
In the next lesson, we will be learning other methods for exception handling.