Below is an example of an implementation subroutine that throws an exception. The returned exception object pointer must be cast into the exception out parameter. This example also utilizes two methods, inherited from sidl.BaseException and implemented in sidl.SIDLException, that aid client-side debugging. The first, setNote, allows the developer to provide a useful error message. The second, add, provides a multi-language traceback capability -- assuming each layer of the call stack invokes add before it propagates the exception.
recursive subroutine ExceptionTest_Fib_getFib_mi(self, n, max_depth, & max_value, depth, retval, exception) use sidl use sidl_BaseInterface use ExceptionTest_Fib use ExceptionTest_NegativeValueException use ExceptionTest_FibException use ExceptionTest_Fib_impl ! DO-NOT-DELETE splicer.begin(ExceptionTest.Fib.getFib.use) use ExceptionTest_TooBigException use ExceptionTest_TooDeepException ! DO-NOT-DELETE splicer.end(ExceptionTest.Fib.getFib.use) implicit none type(ExceptionTest_Fib_t) :: self integer (kind=sidl_int) :: n, max_depth, max_value integer (kind=sidl_int) :: retval, depth type(sidl_BaseInterface_t) :: exception type(sidl_BaseInterface_t) :: except2 ! DO-NOT-DELETE splicer.begin(ExceptionTest.Fib.getFib) type(ExceptionTest_NegativeValueException_t) :: negexc ! ...lines deleted... character (len=*) myfilename parameter(myfilename='ExceptionTest_Fib_Impl.f') retval = 0 if (n .lt. 0) then call new(negexc, except2) if (not_null(negexc)) then call setNote(negexc, & 'called with negative n', except2) call add(negexc, myfilename, 57, & 'ExceptionTest_Fib_getFib_impl', except2) call cast(negexc, exception, except2) call deleteRef(negexc, except2) return endif else ! ...numerous lines deleted.... ! DO-NOT-DELETE splicer.end(ExceptionTest.Fib.getFib) end subroutine ExceptionTest_Fib_getFib_mi
When an exception is thrown, the implementation should deleteRef any references it was planning to return to its caller. In general, when throwing an exception, it is good practice to call set_null on all out and inout array, class, and interface arguments before returning. This makes things work out better for clients who forget to check if an exception occurred or willfully choose to ignore it.