Exception handling in Julia
Last Updated :
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.
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
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:
Exception | Description |
---|
ArgumentError | This exception is thrown when the parameters to a function call do not match a valid signature. |
BoundsError | This exception is thrown if there the user tries to access anarray index beyond the index range. |
CompositeException | This exception provides information about each subtask that throws exception within a task. |
DimensionMismatch | This exception is thrown when objects called do not have matching dimensionality. |
DivideError | This exception is thrown when the user tries to divide by 0(zero). |
DomainError | This exception is thrown when the argument to a function or constructor does not lie in the valid domain. |
EOFError | This exception is thrown when there is no more data left to read in a file. |
ErrorException | This exception is thrown to indicate generic error. |
InexactError | This exception is thrown when the program cannot exactly convert a particular value to type T in a method. |
InitError | This exception is thrown when an error occurs while running __init__ function of a module. |
InterruptException | This exception is thrown when a process is stopped from the terminal using CTRL+C . |
InvalidStateException | This exception is thrown when the program runs into an invalid state. |
KeyError | This exception is thrown when a user tries to access or delete a non-existing element from AbstractDict or Set. |
LoadError | This exception is thrown if an error occurs while importing or using a file. |
OutOfMemoryError | This exception is thrown when a program exceeds the available system memory. |
ReadOnlyMemoryError | This exception is thrown when a program tries to write a memory that is read-only. |
RemoteException | This exception is thrown when exception of a remote computer is thrown locally. The exception specifies the pid of the worker and the corresponding exception. |
MethodError | This exception is thrown when a method with the required type signature does not exist. |
OverflowError | This exception is thrown when result of an expression is too large for the specified type and causes a wrap-around. |
Meta.ParseError | This exception is thrown when an expression passed to the parse function cannot be interpreted as a valid Julia expression. |
SystemError | This exception is thrown when a system call fails. |
TypeError | This exception is thrown when a type assertion fails, or an intrinsic function is called with incorrect argument type. |
UndefRefError | This exception is thrown if an item or field is not defined for the specified object. |
UndefVarError | This exception is thrown when a symbol is not defined in the current scope. |
StringIndexError | This exception is thrown when the user tries to access a string index that exceeds the string length. |
Similar Reads
Handling Missing Data in Julia Nowadays, one of the common problem of big data is to analyse the missing values in that data. Missing values can lead to some major prediction error which is not good for any business point of view. So when we encounter any missing data we have to apply different techniques to deal with missing val
4 min read
Error Handling in MATLAB Error Handling is the approach of creating a program that handles the exceptions thrown by different conditions without crashing the program. For example, consider the case when you are multiplying two matrices of orders (m x n) and (m x n). Now, anyone who has done elementary linear algebra knows t
2 min read
try keyword - Handling Errors in Julia Keywords in Julia are words that can not be used as a variable name because they have a pre-defined meaning to the compiler. 'try' keyword in Julia is used to intercept errors thrown by the compiler, so that the program execution can continue. This helps in providing the user a warning that this cod
2 min read
Functions in Julia A function in Julia is an object that maps a tuple of arguments to a return value. Functions are fundamental building blocks in Julia, allowing you to encapsulate logic for reuse and abstraction. They can represent pure mathematical operations or perform actions that modify the state of other object
4 min read
String concatenation in Julia String concatenation in Julia is a way of appending two or more strings into a single string whether it is character by character or using some special characters end to end. There are many ways to perform string concatenation. Example:Â Input: str1 = 'Geeks' str2 = 'for' str3 = 'Geeks' Output: 'Gee
2 min read
Python Print Exception In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions.Using as keywordas keyword lets us
3 min read
Comments in Julia Comments are the statements in a code that are ignored by the compiler at the time of execution. These statements are written to beautify the code, providing an explanation for the steps that are used in the code. During coding, proper use of comments makes maintenance easier and finding bugs easily
2 min read
if keyword - Conditional evaluation in Julia Keywords in Julia are reserved words that have a specific meaning and operation to the compiler. These keywords can not be used as a variable name, doing the same will stop the execution process and an error will be raised. 'if' keyword in Julia is used to evaluate a condition. If the condition is t
2 min read
How to Install Cplex in Julia? Within the field of mathematical programming and optimization, CPLEX is a very effective tool that is utilized by both practitioners and researchers. Combining CPLEX with Julia, a high-level programming language renowned for its efficiency and simplicity, brings up a world of possibilities for effec
5 min read
Characters in Julia Julia is a dynamic, high-level programming language with high performance and speed that is used to perform operations in scientific computing. It is great for computational complex problems. It is an open-source language so all source code is available easily online. It is as easy to use as Python
2 min read