c++ - 以 C++ 形式捕获异常

标签 c++ visual-studio-2010 exception

我是 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/

相关文章:

c++ - 从 std::ofstream 获取句柄

c++ - 使用互斥锁在 C++ 中复制构造函数

c# - 我如何在项目中引用 "added as link"时的 dll?

visual-studio-2010 - 如何使 Visual Studio 架构比较忽略数据库引用

sql-server - VS2010中sql脚本的tab标签括号中的数字是多少?

python - urllib3 如何查找 Http 错误的代码和消息

exception - 从 Dart 中的映射访问无效键时如何触发异常

c++ - C++ 在编译时是否支持全局 header ?

java - 当值为 null 时将 HashMap 值存储到数据库中

c++ - 更改选项卡颜色中的静态背景 C++