Execeptions are used to handle greaceful errors and unexpected condtions at rntime.
Julia provides following keywords to handle exceptions
- try
- catch
- finally
Julia Exception handle
if you code throws an exception, place code in try block and handle the exception in 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 always placed with indentation space or tab.
finally always executes whether exception 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 exceptions in Julia
Custom exceptions can be created using struct and exception name
struct CustomException <: Exception end
<:
extends Root exception and creates new exception type
CustomException created and you can use it in your code to throw this exception using throw keyword.
The below example
- Create Custom Exception
- throw these exception when an condition satisfies inside a function
- handle this exception using
try
,catch
andfinally
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