我在Visual Studio中编写的c ++类中具有此功能:
int info::connectSession()
{
std::string _ErrMsg;
std::string _ErrScope;
int _RetVal = 0;
MyException errMsg;
int port = 22;
try
{
if (my_ssh_session == NULL) {
std::cout << "Error creating ssh session" << std::endl;
throw errMsg;
return 0;
}
ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, (const void*)(authentication.ip));
ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, (const void*)(authentication.userName));
ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port);
int rc = ssh_connect(my_ssh_session);
if (rc != SSH_OK) {
std::cout << "Error with connecting" << std::endl;
_ErrMsg = ssh_get_error(my_ssh_session);
ssh_free(my_ssh_session);
_RetVal = -1;
_ErrScope = "Connecting";
//throw std::runtime_error("Error with :" + _ErrScope + _ErrMsg.c_str());
throw errMsg;
}
rc = ssh_userauth_password(my_ssh_session, NULL, (const char*)(authentication.pw));
if (rc != SSH_AUTH_SUCCESS) {
std::cout << "Authentication failed " << ssh_get_error(my_ssh_session) << std::endl;
_ErrMsg = ssh_get_error(my_ssh_session);
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
_RetVal = -2;
_ErrScope = "Authentication";
//throw std::runtime_error("Error with :" + _ErrScope + _ErrMsg.c_str());
throw errMsg;
}
}
catch (std::exception & e)
{
std::cout << "catcher";
std::cout<< e.what();
}
return _RetVal;
}
我从另一个类的函数中调用此connectionState
函数(我在一个共享库中拥有这两个类):
const int smc_getCoreNumbers(Authorization *autho)
{
info *inf = new info(autho);
std::string corenum = inf->coreNumbers();
int num = std::stoi(corenum.c_str());
free(inf);
return num;
}
我编写了一个测试程序来加载我的库(其中包含我提到的这两个类),并在其中传递autho结构:
struct Authorization
{
char* ip;
char* pw;
char* userName;
};
int main(int argc, char **argv)
{
void *lib_handle;
struct Authorization au;
const int (*fn)(struct Authorization*);
au.ip = "my ip";
au.pw = "my pw";
au.userName = "my user";
const char *error;
lib_handle = dlopen("/path/to/shared/library", RTLD_LAZY);
if (!lib_handle)
{
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
fn = dlsym(lib_handle, "smc_getCoreNumbers");
if ((error = dlerror()) != NULL)
{
fprintf(stderr, "%s\n", error);
exit(1);
}
int maxspeed;
maxspeed = (*fn)(&au);
printf("Valx=%d\n",maxspeed);
dlclose(lib_handle);
return 0;
}
和MyException类:
class MyException : public exception
{
const char* what() const throw () {
return "C++ Exception";
}
};
当pw
或user
或ip
错误时,我曾使用异常处理来抛出某些错误。但是当我向它发送错误信息时,我的程序并没有在catch范围内停止,并且继续调试直到其他函数崩溃为止。使用异常处理时我做错什么了吗?