1

I am trying to catch this error but this code does not work. I tried to add different catch conditions but none seem to work. Is it possible to catch this error?

#include <iostream>
#include <exception>
#include <stdexcept>

void myFunction(int* ptr) {
  int y = 3;
}

int main() {
  try {
    int x = 5;
    myFunction(x); // call function with invalid parameter
  }
  catch (const std::invalid_argument& ia) {
    std::cerr << "Invalid argument: " << ia.what() << '\n';
  }
  catch(const std::exception& e) {
    std::cerr << "Invalid conversion error: " << e.what() << '\n';
  }
  catch(...) {
    std::cerr << "Error" << '\n';
  }
  return 0;
}

Error message:

main.cpp: In function ‘int main()’:
main.cpp:20:16: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
   20 |     myFunction(x); // call function with invalid parameter
      |                ^
      |                |
      |                int
main.cpp:13:22: note:   initializing argument 1 of ‘void myFunction(int*)’
   13 | void myFunction(int* ptr) {
      |                 ~~~~~^~~
pyar23
  • 19
  • 2
  • 10
    code that does not compile cannot throw a runtime exception. – 463035818_is_not_an_ai Mar 28 '23 at 15:41
  • 2
    in case you are coming from Java or other similar more modern languages, there is much to unlearn. C++ does not work like this. (though I also don't know how this would compile in Java or others) – 463035818_is_not_an_ai Mar 28 '23 at 15:41
  • 2
    c++ cannot be learned by trial and error. You need to follow a course or book, https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – 463035818_is_not_an_ai Mar 28 '23 at 15:43
  • 1
    I am kicking myself for not realizing it is a compilation error and not a runtime error. Thank you! – pyar23 Mar 28 '23 at 16:29
  • 1
    @463035818_is_not_a_number In Java, it is known as [**"boxing"**](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html): "*Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an `int` to an `Integer`, a `double` to a `Double`, and so on. If the conversion goes the other way, this is called unboxing.*" – Remy Lebeau Mar 28 '23 at 16:58
  • don't kick too hard, c++ has more pitfalls just around the next corner – 463035818_is_not_an_ai Mar 28 '23 at 17:03

1 Answers1

2

If you want to make a pointer that points to x, you need to put the ampersand & symbol before the variable, that will give you a pointer to x.

Do it like this:

myFunction(&x);

Now it will work, and you don't need to put it into a try/catch block.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
JacobDev
  • 65
  • 6