Julia Try Catch Finally
A finally block is code that runs no matter how a try block ends. It runs after success, and it runs after a caught error.
Finally runs after success
The try block prints its work. The finally block prints its marker after it.
try
println("Work done")
finally
println("Finally ran")
endFinally runs after a caught error
Division by zero fails and catch prints a fixed message. The finally block still prints its marker.
try
div(1, 0)
catch
println("Caught fixed")
finally
println("Finally marker")
endFinally runs before a return finishes
The function returns from inside try. The finally block prints its marker before the caller prints the result.
function work()
try
return "done"
finally
println("Cleanup ran")
end
end
println(work())Example
function safe_div(a, b)
try
println(div(a, b))
catch
println("Division failed")
finally
println("Finished")
end
end
safe_div(10, 2)
safe_div(10, 0)Key points
- Finally: A finally block runs whether or not an error occurred.
- Success case: When try succeeds, the finally block still runs after it.
- Error case: When an error is caught, the finally block still runs after catch.
- Marker: A printed marker in finally proves that finally ran.
- Cleanup: Finally is a good place for cleanup that must always happen.
In this example, safe_div divides 10 by 2 and then divides 10 by 0. The first call prints 5, the second prints a fixed failure message, and finally prints Finished after each call.
Note
Finally runs even when a function returns from inside try.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
When does a finally block run?