Exception handling in Julia

10 May, 2022
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.
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")endprintln("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
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
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
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())    endcatch e    println("Second catch block")end
Output:
3.0
Argument less than 5
Second catch block
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
Julia provides some built-in Exceptions, which are as follows:
sagartomar9927
Picked
R Error-handling
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Searching in Array for a given element in Julia
String concatenation in Julia
Vectors in Julia
String to Number Conversion in Julia
Getting rounded value of a number in Julia - round() Method
Tuples in Julia
Formatting of Strings in Julia
Creating array with repeated elements in Julia - repeat() Method
Storing Output on a File in Julia
Working with DataFrames in Julia