如何在F#中抛出有意义的异常并在C#中捕获它们?
使用以下代码:
F#Library:
module Test
exception TestExc of string
let throwit message : unit=
raise (TestExc("custom exception with message: " + message))
C#客户端:
namespace TestExc
{
class Program
{
static void Main(string[] args)
{
try
{
Test.throwit("Hi there");
}
catch (Test.TestExc te)
{
Console.WriteLine("Caught exception with message: " + te.Message);
}
}
}
}
我收到以下消息:
Caught exception with message: Exception of type 'Test+TestExc' was thrown.
但我希望将Hi there
视为已捕获的异常消息。
以下F#等价物是什么?
class CSTestExc:System.Exception
{
public CSTestExc(String message) : base(message) { }
}
答案 0 :(得分:5)
使用exception TestExc of string
创建例外而不是创建例外:
type MyExp (msg:string) =
inherit Exception(msg)