In this recipe, you will discover how to make use of Julia's exception handling mechanism.
For this recipe, no package installation is required.
Sometimes executing code results in an unexpected error. A typical example could be working with a file:
- Start the Julia command line and define the following two logger functions that append a log to a file:
functionloglines(filename, lines...) f=open(filename, "a") foreach(line-> (println(f, line)), lines) sqrt(-2) close(f) end
- Now, run the functions in the REPL:
julia> loglines("mylog.txt", "Test log:") ERROR: DomainError with -2.0: sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Thetry
-catch
block makes it possible to suppress the error:
julia>try loglines("mylog.txt", "Test log:") catche...