Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch char * exceptions in C++

Tags:

c++

exception

I am trying to catch a char * type exception in main() but the program crashes with the following message: terminate called after throwing an instance of 'char const*' Here is the code:

#include <iostream>

int main ()
{
    char myarray[10];
    try
    {
        for (int n=0; n<=10; n++)
        {
            if (n>9)
            throw "Out of range";
            myarray[n]='a';
        }
    }
    catch (char * str)
    {
        std::cout << "Exception: " << str << std::endl;
    }
    return 0;
}
like image 821
Mutai Mwiti Avatar asked Oct 29 '15 09:10

Mutai Mwiti


People also ask

What is the syntax for catching any type of exceptions?

Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

How do you use try and catch in C?

It uses a long jump out of the current function to the try block. The try block then uses an if/else to skip the code block to the catch block which check the local variable to see if it should catch. This uses a global pointer so the longjmp() knows what try was last run.

Is there exception handling in C?

The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.

What is Rethrowing an exception in C++?

If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.


2 Answers

Use const:

catch (const char * str)
    {
        std::cout << "Exception: " << str << std::endl;
    }
like image 142
wrangler Avatar answered Sep 20 '22 05:09

wrangler


You don't want to catch char*.

I don't know where this idea comes from that string literals are char*: they're not.

String literals are const char[N] which decays to const char*.

Catch const char*.

Your program is being terminated because, at present, you're actually not handling your exception!

like image 39
Lightness Races in Orbit Avatar answered Sep 21 '22 05:09

Lightness Races in Orbit