如何在F#中使用有意义的消息抛出异常?

时间:2011-06-16 10:34:44

标签: c# exception f#

如何在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) { }
}

1 个答案:

答案 0 :(得分:5)

使用exception TestExc of string创建例外而不是创建例外:

type MyExp (msg:string) = 
        inherit Exception(msg)