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.
ERROR: LoadError: DomainError: sqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)). Stacktrace:  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.
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.
4.0 3.0 5.0 ERROR: LoadError: DomainError: Stacktrace:  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.
No such file exists After exception
Throwing An Exception
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.
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.
3.0 Argument less than 5 ERROR: LoadError: Stacktrace:  error() at ./error.jl:30 while loading /home/cg/root/945981/main.jl, in expression starting on line 13
Throwing error from catch block
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
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:
|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 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.|
- Difference between System Level Exception and Application Level Exception in C#
- Scala | Exception Handling
- Exception Handling in Node
- Exception Handling in Kotlin with Examples
- try keyword - Handling Errors in Julia
- File Handling in Julia
- Handling Missing Data in Julia
- Julia end Keyword | Marking end of blocks in Julia
- Julia function keyword | Create user-defined functions in Julia
- Julia continue Keyword | Continue iterating to next value of a loop in Julia
- Julia break Keyword | Exiting from a loop in Julia
- Julia local Keyword | Creating a local variable in Julia
- Julia global Keyword | Creating a global variable in Julia
- Catch and Throw Exception In Ruby
- Why does canvas.toDataURL() throws a security exception?
- Perl | File Handling Introduction
- Error Handling in Perl
- File Handling in Ruby
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.