我是 C++ 新手。我正在尝试用 C++ 编写程序,但在使用 e.what()
时出现错误.我包括了#include <exception>
, 但我得到 error C2664 - Cannot convert parameter 1 from const char* to system::string ^
.
这是代码。
#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();
}
}
};
}
最佳答案
codeFile
是非托管代码,抛出非托管异常,因此您可以正确捕获异常。您需要做的就是将 const char *
转换为 String^
以将其放入您的 UI。
String类有一个接受 char*
的构造函数(char* 在 C# 中是 SByte*)。 label1->Text = gcnew String(e.what());
应该可以解决您的问题。
也就是说,您可以使用托管流对象。这将为您提供托管异常而不是非托管异常,以及与其余托管代码的更好的互操作性。看看FileStream ,看看是否满足您的需求。
关于c++ - 以 C++ 形式捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14385814/