user1392095
user1392095

Reputation:

Catch exception in C++ Form

I am new to C++. I am trying to make a program in C++, but I get an error, when I use e.what(). I've included #include <exception>, but I get error C2664 - Cannot convert parameter 1 from const char* to system::string ^.

Here's the code.

#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();
        }
         }
 };
}

Upvotes: 0

Views: 1097

Answers (2)

David Yaw
David Yaw

Reputation: 27864

codeFile is unmanaged code, throwing an unmanaged exception, so you're catching the exception properly. All you need to do is convert the const char * to a String^ to put it in your UI.

The String class has a constructor that takes a char* (char* is SByte* in C#). label1->Text = gcnew String(e.what()); should solve your problem.

That said, you could use the managed stream objects. This would give you managed exceptions instead of unmanaged, and greater interoperability with the rest of your managed code. Take a look at FileStream, and see if that meets your needs.

Upvotes: 1

Matthew Clark
Matthew Clark

Reputation: 24

This is a bit of a guess but try changing

catch (exception &e)

to

catch (exception& e)

Upvotes: -1

Related Questions