2011-06-16 73 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

相關問題