2013-01-17 102 views
0

我是C++新手。我想用C++编写一个程序,但是当我使用e.what()时出现错误。我已经包含#include <exception>,但我得到error C2664 - Cannot convert parameter 1 from const char* to system::string ^以C++形式捕获异常

这是代码。

#pragma once 
#include <iostream> 
#include <fstream> 
#include <exception> 
#include <string> 

namespace SilverthorneTechnologiesSchoolDashboard { 

using namespace System; 
using namespace System::ComponentModel; 
using namespace System::Collections; 
using namespace System::Windows::Forms; 
using namespace System::Data; 
using namespace System::Drawing; 
using namespace std; 

//Form parameters 

#pragma endregion 
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) { 
     ifstream codeFile; 
     try{ 
      codeFile.open("userDetails.info"); 
     } 
     catch (exception &e) 
     { 
      label1->Text = e.what(); 
     } 
     } 
}; 
} 
+3

这不是C++。 – aschepler

+2

您需要将此标记为另一种语言,因为它不是C++。 – juanchopanza

回答

2

codeFile是托管代码,抛出异常的非托管,所以你正确地捕捉异常。您只需将const char *转换为String^即可将其放入您的用户界面。

String类有一个构造函数,它需要一个char*(在C#中char *是SByte *)。 label1->Text = gcnew String(e.what());应该可以解决你的问题。

也就是说,您可以使用托管流对象。这将为您提供受管理的异常,而不是非托管的,以及与其他托管代码更好的互操作性。看看FileStream,看看是否符合你的需求。

-1

这是一个有点猜测,但尝试改变

catch (exception &e) 

catch (exception& e) 
+0

不,对不起。它不起作用 –