2011-06-16 56 views
2

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

回答

5

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

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

谢谢,成功了! – khachik 2011-06-16 12:03:15