Open In App

Exception handling in Julia

Last Updated : 10 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Any unexpected condition that occurs during the normal program execution is called an Exception. Exception Handling in Julia is the mechanism to overcome this situation by chalking out an alternative path to continue normal program execution. If exceptions are left unhandled, the program terminates abruptly. The actions to be performed in case of occurrence of an exception is not known to the program. The process of avoiding the compiler to crash on such exceptions is termed as Exception Handling.

Exception Handling

Julia allows exception handling through the use of a try-catch block. The block of code that can possibly throw an exception is placed in the try block and the catch block handles the exception thrown. The exception propagates through the call stack until a try-catch block is found. Let us consider the following code, Here we try to find the square root of -1 which throws "DomainError" and the program terminates. 

Python3
println(sqrt(-1))

Output:

ERROR: LoadError: DomainError:
sqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).
Stacktrace:
 [1] sqrt(::Int64) at ./math.jl:434
while loading /home/cg/root/945981/main.jl, in expression starting on line 1

In absence of a try-catch block the program terminates abruptly. However, we can prevent the termination of program by handling the exception gracefully using a try-catch block. 

Python3
println("Before Exception")
try
    sqrt(-1)
catch
    println("Cannot find the square root of negative numbers")
end
println("After Exception")

Output:

Before Exception
Cannot find the square root of negative numbers
After Exception

The try-catch block also allows the exception to be stored in a variable. The method of using the catch block to handle multiple types of Exception is called Canonical method. The following example calculates the square root of the third element of x if x is indexable, otherwise assumes x is a real number and returns its square root. 

Python3
sqrt_third(x) = try
        println(sqrt(x[3]))
    catch y
        if isa(y, DomainError)
            println(sqrt(complex(x[3], 0)))
        elseif isa(y, BoundsError)
            println(sqrt(x))
        end
    end


sqrt_third([1 9 16 25])
sqrt_third([1 -4 9 16])
sqrt_third(25)
sqrt_third(-9)

Output:

4.0
3.0
5.0
ERROR: LoadError: DomainError:
Stacktrace:
 [1] sqrt_third(::Int64) at /home/cg/root/945981/main.jl:7
while loading /home/cg/root/945981/main.jl, in expression starting on line 15

Use of Finally clause

The finally block runs irrespective of the occurrence of an exception. Code inside the finally block can be used to close resources like opened files or other cleanup work. 

Python3
try
    f = open("file.txt")
catch
    println("No such file exists")
finally
    println("After exception")
end

Output:

No such file exists
After exception

Throwing An Exception

The throw() function can be used to throw custom exceptions. The following examples shows an error being thrown from a function and handled by the catch block. The error() function is used to produce an ErrorException. 

Python3
function f(x)
    if(x < 5)
        throw(error())
    end
    return sqrt(x)
end

try
    println(f(9))
    println(f(1))
catch e
    println("Argument less than 5")
end

Output:

3.0
Argument less than 5

Exceptions can also be thrown from the catch block. The catch block may include some code to handle the caught exception and then rethrow an exception. This exception must be handled by another try-catch block in the same method or any other method in the call stack. The exception propagates all throughout to the main function if it is left uncaught. 

Python3
function f(x)
    if(x < 5)
        throw(error())
    end
    return sqrt(x)
end

try
    println(f(9))
    println(f(1))
catch e
    println("Argument less than 5")
    throw(error())
end

Output:

3.0
Argument less than 5
ERROR: LoadError: 
Stacktrace:
 [1] error() at ./error.jl:30
while loading /home/cg/root/945981/main.jl, in expression starting on line 13

Throwing error from catch block

Python3
function f(x)
    if(x < 5)
        throw(error())
    end
    return sqrt(x)
end

try
    try
        println(f(9))
        println(f(1))
    catch e
        println("Argument less than 5")
        throw(error())
    end
catch e
    println("Second catch block")
end

Output:

3.0
Argument less than 5
Second catch block

One line try-catch

try sqrt(x) catch y end

This means try sqrt(x), and if an exception is thrown, pass it to the variable y. Now if the value stored in y must be returned then the catch must be followed by a semicolon.

try sqrt(x) catch; y end
Python3
try println(sqrt(-9)) catch; y end

Output:

ERROR: LoadError: UndefVarError: y not defined
while loading /home/cg/root/945981/main.jl, in expression starting on line 1
Built-in Exceptions

Julia provides some built-in Exceptions, which are as follows:

ExceptionDescription
ArgumentErrorThis exception is thrown when the parameters to a function call do not match a valid signature.
BoundsErrorThis exception is thrown if there the user tries to access anarray index beyond the index range.
CompositeExceptionThis exception provides information about each subtask that throws exception within a task.
DimensionMismatchThis exception is thrown when objects called do not have matching dimensionality.
DivideErrorThis exception is thrown when the user tries to divide by 0(zero).
DomainErrorThis exception is thrown when the argument to a function or constructor does not lie in the valid domain.
EOFErrorThis exception is thrown when there is no more data left to read in a file.
ErrorExceptionThis exception is thrown to indicate generic error.
InexactErrorThis exception is thrown when the program cannot exactly convert a particular value to type T in a method.
InitErrorThis exception is thrown when an error occurs while running __init__ function of a module.
InterruptExceptionThis exception is thrown when a process is stopped from the terminal using CTRL+C .
InvalidStateExceptionThis exception is thrown when the program runs into an invalid state.
KeyErrorThis exception is thrown when a user tries to access or delete a non-existing element from AbstractDict or Set.
LoadErrorThis exception is thrown if an error occurs while importing or using a file.
OutOfMemoryErrorThis exception is thrown when a program exceeds the available system memory.
ReadOnlyMemoryErrorThis exception is thrown when a program tries to write a memory that is read-only.
RemoteExceptionThis exception is thrown when exception of a remote computer is thrown locally. The exception specifies the pid of the worker and the corresponding exception.
MethodErrorThis exception is thrown when a method with the required type signature does not exist.
OverflowErrorThis exception is thrown when result of an expression is too large for the specified type and causes a wrap-around.
Meta.ParseErrorThis exception is thrown when an expression passed to the parse function cannot be interpreted as a valid Julia expression.
SystemErrorThis exception is thrown when a system call fails.
TypeErrorThis exception is thrown when a type assertion fails, or an intrinsic function is called with incorrect argument type.
UndefRefErrorThis exception is thrown if an item or field is not defined for the specified object.
UndefVarErrorThis exception is thrown when a symbol is not defined in the current scope.
StringIndexErrorThis exception is thrown when the user tries to access a string index that exceeds the string length.

Next Article
Article Tags :

Similar Reads