Throwing string

Hey everyone.
I'm trying to throw an error. And to make it simple to understand i would like to type a string. I have trie:

 
throw "ERROR IN NAVIGATION R1 = R2. IS v and R1 in same component";


resulting in the following errror:
terminate called after throwing an instance of 'char const*'

Any know a solution which can solve my problem.
Thanks for your help
That's not a string. It's a char const*. Are you catching it?
Last edited on
Nope i don't catch it. Is that neccesary?

As far as I knew, a string is a array of char's. So i believe that char const*=string. Am i wrong?
Am i wrong?
This being C++, yes, you are wrong. In C++, a string is a proper object created like this:
string anObject;
An array of chars is often called a string when coding in C. C++ has proper string objects.

An exception is thrown until some code catches it. If you do not write code to catch it, nothing will catch it and the program will terminate.
Last edited on
Nope i don't catch it. Is that neccesary?
Yes, you DO need to catch it.

As far as I knew, a string is a array of char's. So i believe that char const*=string. Am i wrong?
Mostly.
A string isn't exactly a const char *. It is a class that contains a const char * and two integers that denote the size and allocated size of the array.

A const char * is just a pointer (an array, to simplify).

If you want to throw a string, you must:

 
throw std::string("ERROR IN NAVIGATION R1 = R2. IS v and R1 in same component");
I'm trying to throw an error. And to make it simple

To make it simple, you shouldn't invent new and unusual ways to do it.

Just throw an *exception* of the type you think is appropriate:

throw std::runtime_error("ERROR IN NAVIGATION");

Then catch it by reference to the base exception class (or to the one you threw, if you have many different ones) and print the what()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdexcept>
#include <iostream>

void f()
{
  throw std::runtime_error("ERROR IN NAVIGATION");
}

int main()
{
   try {
       f();
   } catch(const std::exception& e) {
       std::cout << "Caught exception: " << e.what() << '\n';
   }
}
Last edited on
Hey everyone.
Thanks a lot. I then try to make a try catch to throw my error as you told me.

I have tried to make do as Cubbi suggest, but i recieve an error at the thrown runtime_error:

Function 'runtime_error' could not beresolved C++

Any know what to do?
Did you include stdexcept?
Am i wrong?

I don't think you are wrong. What you have is a C string. What Moschops is talking about is std::string. They are both strings, but different kinds.
Topic archived. No new replies allowed.