Sage-Code Laboratory
index<--

Julia Exceptions

When something goes wrong the execution of the program can be stopped. This is called an exception. We can create exceptions on purpose to show to the user that something has gone wrong and we can print a message to explain the situation. In Julia there are pre-define exceptions that have a name and are automatically created by the system in certain situations.

Handling Exceptions

We have two cases. One is when you wish to "catch" the exception and continue the program. Another is we wish to "finalize". That is to execute something important before the program stop execution. We use a try block with two keywords: catch and finally. You can use both clauses or only one depending on the case.

Syntax:

# try block syntax
try
    [executable_region]
catch
    [exception_handler]
finally
    [something_important]
end

Example:

# opening and closing a file
f = open("file")
try
    # operate on file
finally
    close(f)
end

Example:

# catching an error
x = 0
try
    z= y/x
catch err
    if isa(err, ZeroDivide)
        println("error division by zero")
    end
end

Note: In the previous example we catch the error and copy the error in variable err. Then we use function isa() to analyze the error type. We can create errors using error() function and throw() function. Most of the type we do not catch errors and we do not create error handlers in programs.

Final Note:Our introductory tutorial ends here but not your journey. There is more to learn from the official user manual. Follow the link below. I hope you will enjoy this language and later maybe you help us to improve our tutorial for next students. We look forward for feedback on Twitter and Discord about your experience. Have fun!

Go back: Julia Tutorial