繁体   English   中英

以C ++形式捕获异常

[英]Catch exception in C++ Form

我是C ++的新手。 我试图用C ++ e.what()程序,但是当我使用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 ,看是否满足您的需求。

这有点猜测,但是请尝试更改

catch (exception &e)

catch (exception& e)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM