I send this line to F# interactive console in Visual Studio
assert (2=3)
To my surprise, the console does not report errors, but
val it : unit = ()
Similarly, if I run
printf ("hello!")
assert (2=3)
printf ("hello2")
on an REPL, I got "hellohello2" without any error messages.
How could I make the F# interactive tell me 2=3 is wrong?
Under the cover, the assert
keyword translates to a method call to the Debug.Assert
method from the .NET library (see the method documentaiton). This has a conditional compilation attribute [Conditional("DEBUG")]
, meaning that the call is only included if the symbol DEBUG
is defined.
By default, this is not the case in F# Interactive. You can do that by adding --define:DEBUG
to the command line parameters for fsi.exe
. This will be somewhere in the options of your editor, depending on what you are using. For example, in Visual Studio, you need something like this:
EDIT: How to do something like this if you do not want to modify the command line parameters? This really depends on what exactly behaviour you want. The default behaviour of assert
is that it shows a message box where you can either terminate the program or ignore the error. You could do that using:
open System.Windows.Forms
let ensure msg b =
let res =
MessageBox.Show("Assertion failed: " + msg +
"\n\nDo you want to terminate the exection? Press 'Yes' " +
"to stop or 'No' to ignore the error.", "Assertion failed",
MessageBoxButtons.YesNo)
if res = DialogResult.Yes then exit 42
ensure "Mathematics is broken" (2=3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With