Handling exceptions in Julia
In this recipe, you will discover how to make use of Julia's exception handling mechanism.
Getting ready
For this recipe, no package installation is required.
Note
In the GitHub repository for this recipe you will find the commands.txt
file that contains the presented sequence of Julia commands.
How to do it...
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...