Im tryig to use try throw and catch to catch the exception i
I\'m tryig to use try, throw, and catch to catch the exception if the user passes in an empty string, but it\'s not working can anyone help me with my code?
LCR_cipher::LCR_cipher(const char * context_string, const char * keys_string)
{
//try allocate memory for context and copy characters over
try
{
encrypted = false;
if (strlen(context_string) != NULL && strlen(keys_string) != NULL)
{
context = new char[strlen(context_string) + 1];
for (int i = 0; i < strlen(context_string); i++) {
context[i] = context_string[i];
}
context[strlen(context_string)] = \'\\0\'; //add a null character at the end
//allocate memory for keys and copy characters over
keys = new char[strlen(keys_string) + 1];
for (int i = 0; i < strlen(keys_string); i++)
{
keys[i] = keys_string[i];
}
keys[strlen(keys_string)] = \'\\0\';
}
else
throw 0;
}
catch (int x)
{
cout << \"the string is empty so outputting a \" << x << endl;
}
}
Solution
LCR_cipher::LCR_cipher(const char * context_string, const char * keys_string)
{
//try allocate memory for context and copy characters over
try
{
encrypted = false;
//It\'s not working Because of strlen return integer value and you compare it with NULL.
if (strlen(context_string) != 0 && strlen(keys_string) != 0)
{
context = new char[strlen(context_string) + 1];
for (int i = 0; i < strlen(context_string); i++)
{
context[i] = context_string[i];
}
context[strlen(context_string)] = \'\\0\'; //add a null character at the end
//allocate memory for keys and copy characters over
keys = new char[strlen(keys_string) + 1];
for (int i = 0; i < strlen(keys_string); i++)
{
keys[i] = keys_string[i];
}
keys[strlen(keys_string)] = \'\\0\';
}
else
throw \"the string is empty so outputting a \";
}
catch (const char* msg)
{
cout << msg << endl;
}
}

