Stack if there is no Error

Is the only way to access the call stack without an error object?

You can throw your own to catch if you need the stack, but it is the only way at this time.

try
  raise new RuntimeException
catch ex as RuntimeException
  // ex.Stack

end try

In general, if you need the stack for anything other than error reporting, your code design “suboptimal.” There was a relatively recent bump to a year old thread where I wasn’t the only expert to say this.

2 Likes

Yeah, its to trap a case where data ‘vanishes’ unpredictably, and I want to know what’s been happening before it occurs.

I can tell when it has happened, but not why it happened, and cannot recreate in my own testing.

That’s the perfect use case and just for fun you could even use UnsupportedFormatException

You can also use BacktraceMBS if you want the stack without throwing an exception.

dim stack() as string = BacktraceMBS

I believe that this is macOS, Linux, and iOS only though.

In the past I used this:

Public Function CalledBy() As String
  // returns the signature of the method that called the current method
  // similar to CurrentMethodName
  // this is a String, not an Object nor Introspection Reference. So IsA queries are not possible on the result
  
  var stack() As String  
  stack = CallStack( )
  
  // 0 is this method
  // 1 is the method that called this
  // 2 is the method that was asked for
  'Select Case stack.Ubound 
  Select Case stack.LastIndex
  Case Is >= 2
    Return stack(2)
  Case 1 
    //this can happen if we are called from the run event of an thread
    Return stack(1) 
  End Select
End Function

Public Function Callstack() As String( )
  // returns the signatures of the current CallStack
  // workaround for <feedback://showreport?report_id=14501>
  
  var result() As String
  
  Try
    #Pragma BreakOnExceptions OFF
    Raise New RuntimeException
  Catch e As RuntimeException
    var stack() As String = e.Stack
    If stack.LastIndex >= 2 Then
      // 0 is this Method
      // 1 is requesting Method
      // 2 is first calling Method
      stack.Remove(0)
    End If
    result = stack
  Finally
    #Pragma BreakOnExceptions Default
  End Try
  
  Return result
End Function