Exceptions are used to handle graceful errors and unexpected conditions at runtime.

Julia provides the following keywords to handle exceptions

  • try
  • catch
  • finally

Julia Exception handle

if your code throws an exception, place the code in a try block and handle the exception in the catch block

try
    // code block that throws an exception
catch e
    // exception handle
finally
    // code cleanup
end

try, catch, and finally are keywords in Julia. code statements inside these are always placed with indentation space or tab.

finally always executes whether an exception is thrown or not.

Here is an example

try
  sqrt("12a")
catch e
  println(e)
  println("invalid number")

finally
  println("always execute")
end

Output:

MethodError(sqrt, ("12a",), 0x0000000000007eb1)
invalid number
always execute

How to create a custom exception in Julia

Custom exceptions can be created using struct and exception name

struct CustomException <: Exception end

<: extends the Root exception and creates a new exception type

CustomException was created and you can use it in your code to throw this exception using the throw keyword.

The below example

  • Create Custom Exception
  • throw this exception when an condition satisfies inside a function
  • handle this exception using try, catch, and finally
struct CustomException <: Exception end

positive(number) = number>0 ? number : throw(CustomException(number, "negative not allowed"))
try
 positive(-1)
catch e
  println(e)
  println("invalid number")

finally
  println("always execute")
end