Is it possible to try using a package?
try
using A
catch e
showerror(STDOUT, e)
end
unsupported or misplaced expression using
I am expecting to see error message like
using A
LoadError: ArgumentError: A not found in path
using is only allowed at the top level scope. A workaround can be to use eval(:(using A)) instead of using A and then the try-catch works as expected.
The difference comes from using eval which evaluates its expression argument in the top level scope.
julia> try
eval(:(using A))
catch e
showerror(STDOUT, e)
end
ArgumentError: A not found in path
Related
val SOME i = Int.fromString e
I have a line like this on my code and smlnj shows me this warning
vm.sml:84.7-84.32 Warning: binding not exhaustive
SOME i = ...
Is this bad practice? Should I use a function to handle the option or am I missing something?
If you're just working on a small script you'll run once, it's not necessarily bad practice: If Int.fromString e fails (and returns NONE instead of SOME _), then the value binding will fail and an exception will be raised to the appropriate handler (or the program will exit, if ther is no handler). To disable this warning, you can run the top-level statement (for SML-NJ 110.96): Control.MC.bindNonExhaustiveWarn := false;.
As an alternative approach, you could throw a custom exception:
val i =
case Int.fromString e
of SOME i => i
| NONE => raise Fail ("Expected string value to be parseable as an int; got: " ^ e)
The exception message should be written in a way that's appropriate to the provenance of the e value. (If e comes from command-line input, the program should tell the user that a number was expected there; if e comes from a file, the program should tell the user which file is formatted incorrectly and where the formatting error was found.)
As yet another alternative: If your program is meant to be long-running and builds up a lot of state, it wouldn't be very user-friendly if the program crashed as soon as the user entered an ill-formed string on the command line. (The user would be quite sad in this case, as all the state they built up in the program would have been lost.) In this case, you could repeatedly read from stdin until the user types in input that can be parsed as an int. This is incidentally more-or-less what the SML/NJ REPL does: instead of something like val SOME parsedProgram = SMLofNJ.parse (getUserInput ()), it would want to do something like:
fun getNextParsedProgram () =
case SMLofNJ.parse (getUserInput ())
of NONE => (print "ERROR: failed to parse\n"; getNextParsedProgram ())
| SOME parsedProgram => parsedProgram
In summary,
For a short-lived script or a script you don't intend on running often, turning off the warning is a fine option.
For a program where it's unexpected that e would be an unparseable string, you could raise a custom exception that explains what went wrong and how the user can fix it.
For longer-lived programs where better error handling is desired, you should respect the NONE case by pattern-matching on the result of fromString, which forces you to come up with some sort of error-handling behavior.
I am trying to stack multiple exception conditionals into a single line. How can I do this in Julia?
You need to check the type of the error in the catch block, usually using an if-else tree. Anything else will naturally follow from the if-else syntax.
Here's what I would consider the "canonical" way of doing it:
try
# throw some error here
catch e
if e isa ErrorException
# do something
elseif e isa ArgumentError
print("So much for multiple dispatch")
else
rethrow(e)
end
end
You could shrink this into one line using the ternary operator, but it's probably not worth it.
Does R provide any support for targetting exception handling to only specific exceptions?
In Python, for example, one can narrow down exception-handling to specific exception types; e.g.:
try:
return frobozz[i]
except IndexError:
return DEFAULT
In this example, the exception handling will kick in only if i is an integer such that i >= len(frobozz) or i < -len(frobozz), but will not catch the exception resulting from, e.g., the case where i is the string "0" (which would be a TypeError, rather than an IndexError).
Wellllll...yes and no, and mostly no.
Every Python exception is wrapped in a particular error class which derives from Error, and Python modules are supposed to raise the "right" kinds of errors. For instance, an index out of range error should throw IndexError. The base language knows about these errors and so you can catch the appropriate error type in your except... clause.
R doesn't do that. Errors are untyped; there's no essential difference between an index out of bounds error and any other error.
That said, you can cheat under certain, very limited, circumstances.
> y <- tryCatch(x[[2]], error = function(e) e)
> y
<simpleError in x[[2]]: subscript out of bounds>
> y$message
[1] "subscript out of bounds"
The key here is the use of the tryCatch function and the error clause. The error clause in a tryCatch is a function of one variable which can perform arbitrary operations on e, which is an object of type 'simpleError' and contains an item named "message". You can parse message and handle interesting cases separately
> y <- tryCatch(x[[2]],
error = function(e) {
if ('subscript out of bounds' == e$message) return(NA) else stop(e))
})
> y
[1] NA
This only works if you can actually detect the error string you want to look for, and that isn't guaranteed. (Then again, it also isn't guaranteed in Python, so things aren't really much different from one another.)
Final question, though: why in Heaven's name are you doing this? What are you really trying to do?
From the finally section here: http://docs.julialang.org/en/release-0.4/manual/control-flow/#finally-clauses, they are using this example:
f = open("file")
try
# operate on file f
finally
close(f)
end
When I run similar code in REPL, this happens:
julia> f = open("myfile.txt")
IOStream(<file myfile.txt>)
julia> try
sqrt(-10)
finally
close(f)
end
ERROR: DomainError:
[inlined code] from none:2
in anonymous at no file:0
Any idea what's the difference?
finally does not catch exceptions. It's for guaranteeing that cleanup steps happen regardless of whether an exception occurred or not. Note the difference between:
try
sqrt(-10)
catch
println("Exception swallowed!")
end
and
try
sqrt(-10)
finally
println("This cleanup happened regardless of whether an exception was thrown.")
end
Often one combines catch and finally:
try
sqrt(-10)
catch
println("Swallowed exception.")
finally
println("...but finally ran regardless.")
end
finally has still done it's job here in the sense that the close() operation has been carried out. You can check this in your code by adding isopen(f) which returns false. You get the error though because you tried to do something that produced it.
try block is always followed by the catch block. in your program you forget to put catch block before finally block.
I can access the basic function of stat library in R when I connect C# and R through statconnector. But if I load a library(), I am not able to call any of its function.
The code I am trying is:
rConn.SetSymbol("n1", 20);
rConn.Evaluate("library(dtw)");
rConn.Evaluate("x1<-rnorm(n1)");
rConn.Evaluate("x2<-rnorm(n1)");
rConn.Evaluate("Score<-dtw(x1,x2,keep.internals=TRUE)");
The error I get is when I run the last line i.e., rConn.Evaluate("Score<-dtw(x1,x2,keep.internals=TRUE)");
The error i get is -
There is no connection for this connection ID (Exception from HRESULT: 0x80040004 (OLE_E_NOCONNECTION))
You will find that with some functions called via StatConnector that you MUST use .EvaluateNoReturn instead of .Evaluate. It makes sense if you recognize that if you examine the class of "Score" (within R) via:
class(Score)
[1] "dtw"
You see that "Score" contains a dtw object. Implicitly whenever you use .Evaluate, you are calling a function with a return value. However, C# doesn't know what to do with a dtw object, so you get a funky error message that make you go hmmm. Try the equivalent of a void call instead:
rConn.EvaluateNoReturn("Score<-dtw(x1,x2,keep.internals=TRUE)");
And you should have no error executing dtw. To get a return value back into C#, while in R, take a look at names(Score) to see which variables are available, then something like
class(Score$normalizedDistance)
"numeric"
to get an idea how to cast the values for C#, as in:
double myDist = (double)rConn.Evaluate("Score$normalizedDistance");
Additional information I found that I received a similar error when calling 10+ concurrent statconnector instances.
The .Evaluate function when returning values would fail on 10% of calculations with the following error
There is no connection for this connection ID (Exception from HRESULT: 0x80040004 (OLE_E_NOCONNECTION))
at StatConnectorCommonLib.IStatConnector.Evaluate(String bstrExpression)
The fix I found to work was to store the result in a variable in R, and use the .EvaluateNoReturn and .GetSymbol to return the results.
StatConnector rConn = new StatConnector();
rConn.Init("R");
rConn.SetSymbol("n1", 20);
rConn.Evaluate ("x1<-rnorm(n1)");
var o = rConn.GetSymbol ("x1");
foreach (double d in o)
Console.WriteLine(d);
rConn.Close();
Check out the following article for my source and examples,
http://www.billbak.com/2010/11/accessing-r-from-clessons-learned/