In standard ML, can you find an exception like "Error: unbound variable or constructor: foo"?

I have this newbie question: in standard ML you can find an exception like "Error: unbound variable or constructor: foo"?

I tried to do this with the following program:

(foo()) handle Error msg => (); 

But the REPL complains: "Error: the non-constructor applies to the argument in the template: Error"

Thanks in advance.

+4
source share
2 answers

First of all, it is handle Error => ... (or handle Error => ... or handle TheSpecificExceptionIWantToCatch => ... ), and not handle Error msg => ... You can only write handle Foo msg => ... if Foo is a constructor with one argument, which, as the error message indicates, Error not.

Secondly, an β€œunbound variable” is a compilation error, not an exception, so it cannot be caught.

+3
source

Just add to your existing answer. I noticed that Chao was trying to "catch" an error based on a message she received trying to execute code. A true exception message in REPL is reported immediately after the line val it = () : unit , indicating that this occurs after the interpretation phase. In addition, in the Standard ML New Jersey v110.76 interpreter, it appears at run time with a message such as:

uncaught exception ExceptionName raised at: filename.sml:linei.columni-linej.columnj

Therefore, without seeing an explicit message in these lines, you should raise the alarm so that the exception is not raised, the pun is not intended. Since the question was how to catch the exception, not the error, I think the exception mechanism should be briefly explained:

  • Somewhere in the code, in the lexical area where it will be used, you need to define an exception binding: exception MyException or exception MyException2 of String
  • Somewhere in the expression, a case is found that deserves to interrupt the normal control flow and thus uses the following primitive to do just that: raise MyException or raise (MyException2("Error in foo"))
  • An exceptional thread interrupt can be captured by a descriptor expression that uses pattern matching in the exception constructor and sends an alternative expression for evaluation. In this case, the expression e1 throws an exception, and the handler returns the expression e2: e1 handle MyException => e2

For more information on how to write clean and elegant exception handlers for complex functions, with restoration of execution, if necessary, read this page on-line records Programming in standard ML by Robert Harper

+1
source

Source: https://habr.com/ru/post/1440556/


All Articles