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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read