When to use #debug, #info, #warn, and #error in Julia - julia

There are currently four different error logging levels: "#debug, #info, #warn, and #error" all of which have a different use case and implications of their use. In general, when is it appropriate to use the different logging macros?

From the docs:
#debug "Verbose debugging information. Invisible by default"
#info "An informational message"
#warn "Something was odd. You should pay attention"
#error "A non fatal error occurred"
Read more in the Julia docs here. In particular, it's important to note that #error does NOT throw an error, it merely logs an error and continues execution. If you want to throw an error, use the error function instead.

Related

Change "Error" label in stop function on R

Is it possible to change the Error label inside the stop() function?
For example:
stop("This is a error!")
Error: This is a error!
change to:
Incorrect: This is a error!
I need to use stop function, not warning or message functions.
There's a risk that this could be confusing for users seeing something that's an stopping the code without explicitly announcing that it's an error.
If you can guarantee that the user is using English, you can hack it a bit using the backspace character (\b) with:
stop("\b\b\b\b\b\b\bIncorrect: This is a error!")
but this relies on knowing how long the word "Error" is in English, a version that also works in other languages would be trickier.
Edited to add that even in English this doesn't work from inside a function:
throw_an_error <- function()stop("\b\b\b\b\b\b\bIncorrect: This is a error!")
throw_an_error()
# Error in throw_an_errIncorrect: This is a error!

Handling of condition objects in R

What exactly happens in
tryCatch(warning("W"),warning = function(c) cat(c$message))
As far as I understand this the call warning("W") creates a condition object c of type warning and then someone (who?) looks for a handler (where? and recognizes the handler how?) and calls the handler on c.
The task of tryCatch is only to "establish" the handlers. What does this mean? In short the question is: how exactly does the condition object get to its handler?
In my experience, tryCatch is used to catch and either ignore or specifically handle errors and warnings. While you can do warnings with this function, I see it more often used with withCallingHandlers (and invokeRestart("muffleWarning")).
The Advanced R book is a good reference for many topics; for this, I'd recommend two chapters:
Exceptions and debugging, where Hadley highlights one key difference:
withCallingHandlers() is a variant of tryCatch() that establishes local handlers, whereas tryCatch() registers exiting handlers. Local handlers are called in the same context as where the condition is signalled, without interrupting the execution of the function. When a exiting handler from tryCatch() is called, the execution of the function is interrupted and the handler is called. withCallingHandlers() is rarely needed, but is useful to be aware of.
Bold emphasis is mine, to highlight that tryCatch interrupts, withCallingHandlers does not. This means that when a warning is raised, nothing else is executed:
tryCatch({warning("foo");message("bar");}, warning=function(w) conditionMessage(w))
# [1] "foo"
tryCatch({warning("foo");message("bar");})
# Warning in tryCatchList(expr, classes, parentenv, handlers) : foo
# bar
Further details/examples are in the Beyond exception handling chapter.
tryCatch executes the expression in a context where anything "raised" is optionally caught and potentially altered, ignored, logged, etc. A common method I see is to accept any error and return a known entity (now without an error), such as
ret <- tryCatch(
something_that_fails(),
error = function(e) FALSE)
Unlike other operating systems that allow precise filters on what to handle (e.g., python and its try: ... except ValueError: syntax, ref: https://docs.python.org/3/tutorial/errors.html#handling-exceptions), R is a bit coarser in that it catches all errors you can get to figure out what kind of error it is.
If you look at the source of tryCatch and trace around its use of its self-defined functions, you'll see that ultimately it calls an R function .addCondHands that includes the list of handlers, matching on the names of the handlers (typically error and warning, though perhaps others might be used?). (The source for that function can be found here, though I don't find it very helpful in this context).
I don't know exactly how to answer "how exactly ... get to its handler", other than an exception is thrown, it is caught, and the handler is executed with the error object as an argument.

R executes code in function when there is a syntax error and function is not explicitly called

This is interesting. I'm on CentOS 6.9, R-3.4.2. I have a code, tmp.R:
main<-function(){
a = 9
print(a) xyz
print("Should never get here")
}
When I run this, Rscript tmp.R, I get
Error: unexpected symbol in:
" a = 9
print(a) xyz"
No traceback available
[1] "Should never get here"
Error: unexpected '}' in "}"
No traceback available
This is pretty confusing because I never actually called main(). In fact, if I remove the syntax error
(3rd line becomes print(a)), and I run it, there isn't any output. This is the expected behavior in my mind.
QUESTION : Why does R execute code in a script when a syntax error occurs, even when the code isn't explicitly called(!)?
EDIT : It turns out that this behavior seems to be due to having options(error=traceback) being set in my .Rprofile. This is undesirable behavior none the less. It would still be desirable to be able to get tracebacks when in interactive mode and not do this strange code execution in non-interactive mode.

How to mix flog.fatal and stop

I am starting to use the futile.logger package. There is a nice FATAL error logging that I would like to use in conjuction with stop.
But say I do :
stop(flog.fatal('crash for some reason'))
I get
[FATAL] [2015-07-06 22:46:54] [base.stop] crash for some reason
Error:
[FATAL] [2015-07-06 22:46:54] [base.stop] crash for some reason
How can I just stop (abort the program), after logging what the flog.fatal logged
So [FATAL] [2015-07-06 22:46:54] [base.stop] crash for some reason and that's it
Your question as stated seems trivial? Just do
flog.fatal('crash for some reason'); stop()
?
(I personally find futile.logger more useful for writing text messages to a file, not to the console, but also print the messages to the console with R's conditions message(), warning(), stop() etc.
The value returned by flog.fatal is a character vector (length 1) which stop prints.
res <- flog.fatal('crash for some reason')
print(res)
As alternative you can use ftry function from the futile.logger package.
> futile.logger::ftry(log("a"))
ERROR [2017-08-22 10:50:51] non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function

How to display errors when parsing with metasexp?

I'm parsing with common lisp library meta-sexp.
When I call a rule like this (entity? (create-parser-context str)), I'm not getting any error if the str is invalid. How to get the errors displayed?
A non-match is not an error unless a rule (entity?) or the code calling it programs a non-match as failure.
See the readme. There is an example rule integer-debug?, in the center of the document, that uses a callback to report the character and position of input that failed to parse an integer.
Since rules return NIL on no-parse, to signal a fatal error: (or (entity? (create-parser-context input)) (error "Input is bad!)) could be used to bail out with an error message from an irrecoverable input error.

Resources