如何在F#中用有意义的消息抛出异常?
问题描述:
如何在F#中抛出有意义的异常并在C#中捕获它们?如何在F#中用有意义的消息抛出异常?
用下面的代码:
F#库:
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) { }
}
答
而不是使用exception TestExc of string
创建异常,创建例外:
type MyExp (msg:string) =
inherit Exception(msg)
谢谢,成功了! – khachik 2011-06-16 12:03:15