Skip to content

Exceptions in Fortran #236

Open
Open
@aradi

Description

@aradi

Based on the discussion on fortran-lang.discourse about the ErrorFx library, a mechanism for exception like error handling should be created.

ErrorFx demonstrates, that such a mechanism is possible with current Fortran already. But it needs a lot of boiler plate code, which in ErrorFx are currently substituted by Fypp-macros. I drafted a possible syntax for all the scenarios we can already handle in ErrorFx. I'd also provide equivalent Fortran code, but probably we can already start discussion, in case somebody sees some general flaws in the concept.

! All errors are extensions of a base type
type, extends(fatal_error) :: io_error
  character(:), allocatable :: name
  integer :: unit = - 1
end type io_error

type, extends(fatal_error) :: allocation_error
  integer :: allocation_size
end type allocation_error
  

subroutine subroutine_with_error(...) throws(io_error, allocation_error)
  ...
  throw io_error(name="somefile.dat")
 ...
end subroutine subroutine_with_error


function function_with_error(...) result(...) throws(io_error)
  ...
  throw io_error(unit=9)
  ...
end function function_with error


! Propagating error upwards
try call subroutine_with_error()

! Propagating error upwards in function call
i = try function_with_error()

! Catching if any error thrown and assign a default value in that case
i = try function_with_error() else -1

! The classical try-catch block
! errorvar is the name of the local variable representing the error which was caught
! If an error is not handled here, it will be automatically propagated upwards
try catch (errorvar)
  i = function_with_error
  ! or altenatively
  call subroutine_with_error()
catch (io_error)
  ! do something
  print *, "UNIT:", errorvar%unit
  ! We pass it upwards as a more generic error
  throw fatal_error :: errorvar
catch (some_other_error)
  ! do something else for this error
end try catch

! A call to a subroutine or a function with error outside of a try should trigger a compiler error
call subroutine_with_error()  ! should trigger compiler error
i = function_with_error()   ! should trigger compiler error as well

Metadata

Metadata

Assignees

No one assigned

    Labels

    Clause 11Standard Clause 11: Execution control

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions