How to throw a specific exception in Julia

An exception is an event that arises during the execution of the program which disrupts the flow of the program and terminates the program. A specific exception will provide exact information about the error to the user. In Julia, we can throw a specific exception using the syntax below.

Syntax

throw(error)

Example

# division function error
function divideBy(dividend, divisor)
if(divisor == 0)
#throwing specific error
throw(DivideError())
end
return dividend/divisor
end
# throws DivideError
println(divideBy(10,0))

Explanation

In the above code snippet,

  • Lines 2–9: We define a function divideBy() to calculate division.

    • Line 3: We check if the given divisor is equal to zero and then throw DivideError.

  • Line 12: We call the function divideBy(), pass 10 as the dividend, and 0 as a divisor.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved