Custom Errors in Fortran

Here’s the translation of the custom errors example from Go to Fortran:

Our first program demonstrates how to create and use custom errors in Fortran. Here’s the full source code:

module custom_errors
  implicit none

  ! A custom error type usually has the suffix "Error"
  type :: ArgError
    integer :: arg
    character(len=:), allocatable :: message
  contains
    procedure :: get_error_message
  end type ArgError

contains
  ! This function is similar to the Error() method in Go
  function get_error_message(this) result(error_msg)
    class(ArgError), intent(in) :: this
    character(len=:), allocatable :: error_msg
    character(len=20) :: arg_str

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

  function f(arg) result(res)
    integer, intent(in) :: arg
    integer :: res
    type(ArgError), allocatable :: err

    if (arg == 42) then
      ! Return our custom error
      allocate(err)
      err%arg = arg
      err%message = "can't work with it"
      res = -1
    else
      res = arg + 3
    end if
  end function f
end module custom_errors

program main
  use custom_errors
  implicit none

  integer :: result
  type(ArgError), allocatable :: ae

  result = f(42)
  
  if (result == -1) then
    allocate(ae)
    ae%arg = 42
    ae%message = "can't work with it"
    print *, ae%arg
    print *, ae%message
  else
    print *, "No error occurred"
  end if

end program main

To run the program, save it as custom_errors.f90 and compile it using a Fortran compiler:

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

In this Fortran version, we’ve created a custom error type ArgError with an associated procedure get_error_message to mimic the Error() method in Go. The f function returns an integer result, with -1 indicating an error occurred.

The main program calls f(42) and checks if an error occurred (result == -1). If so, it creates an ArgError object and prints its contents.

Note that Fortran doesn’t have built-in error handling mechanisms like Go’s error interface or errors.As. Instead, we use a combination of return values and custom types to achieve similar functionality.

This example demonstrates how to create and use custom error types in Fortran, providing a way to handle and report specific error conditions in your code.