Custom Errors in Co-array Fortran

Our example demonstrates how to create custom errors in Co-array Fortran. While Co-array Fortran doesn’t have a built-in error interface like some other languages, we can create a similar concept using derived types and procedures.

module custom_errors
  implicit none
  private

  type, public :: argError
    integer :: arg
    character(len=:), allocatable :: message
  contains
    procedure :: error => argError_error
  end type argError

contains
  function argError_error(this) result(error_message)
    class(argError), intent(in) :: this
    character(len=:), allocatable :: error_message
    character(len=20) :: arg_str

    write(arg_str, '(I0)') this%arg
    error_message = trim(arg_str) // " - " // this%message
  end function argError_error

  function f(arg) result(result_pair)
    integer, intent(in) :: arg
    type result_type
      integer :: value
      type(argError), allocatable :: error
    end type result_type
    type(result_type) :: result_pair

    if (arg == 42) then
      allocate(result_pair%error)
      result_pair%error%arg = arg
      result_pair%error%message = "can't work with it"
      result_pair%value = -1
    else
      result_pair%value = arg + 3
    end if
  end function f
end module custom_errors

program main
  use custom_errors
  implicit none

  type(result_type) :: result
  class(argError), allocatable :: ae

  result = f(42)

  if (allocated(result%error)) then
    ae = result%error
    print *, ae%arg
    print *, ae%message
  else
    print *, "No error occurred"
  end if
end program main

In this example, we define a custom error type called argError with an arg field of type integer and a message field of type character. We also define an error procedure for this type, which is similar to the Error() method in some other languages.

The f function demonstrates how to use this custom error type. If the input argument is 42, it returns a special result with an error. Otherwise, it performs a simple calculation.

In the main program, we call f with the argument 42 and then check if an error occurred. If it did, we print the error details.

To compile and run this program:

$ gfortran -o custom_errors custom_errors.f90
$ ./custom_errors
42
can't work with it

This example shows how to implement a basic error handling mechanism in Co-array Fortran. While it’s not as sophisticated as error handling in some other languages, it provides a way to create and handle custom errors in your Fortran programs.