1

In my program I pass an argument from console and save it to a variable. Let's say

const  string FileName= argv[1];

If there is no argument passing I get this

terminate called throwing an exception

How can I catch an exception and show proper error to user that there is no arguments passed?

1

4 Answers 4

3

argc gives you the size of argv, so check its value before accessing argv. Remember that argv is zero-based, so has bounds argv[0, ..., arrc - 1]. Helpfully, argv[argc] is always set to NULL.

Accessing an invalid element of argv is undefined behaviour.

As a final remark, argv[0] (if it isn't NULL) is the program name.

10
  • (Actually, it is [0, argc]. The last is guaranteed to be NULL. See 3.6.1/2)
    – BoBTFish
    Sep 13, 2013 at 7:31
  • Actually argv[argc] is a valid entry. It should also always be NULL (which is the problem for the OP, he's trying to assign a NULL pointer to a std::string). Sep 13, 2013 at 7:31
  • Isn't the zero element of argv initialized in any case as it was echo? So 1 means you have 1 parameter in argv[1]? or I remember wrong?
    – dhein
    Sep 13, 2013 at 7:33
  • 1
    @Zaibis The name the program was executed with goes in argv[0] (or, according to The Standard, "" is allowed instead), but that is counted in argc. So if argc is 1, the program was executed with no extra arguments.
    – BoBTFish
    Sep 13, 2013 at 7:35
  • @BoBTFish, I wasn't aware of that. I've amended the answer.
    – Bathsheba
    Sep 13, 2013 at 7:35
1

Your main has two arguments - argv and argc. While argv stores the arguments passed to your program argc stores their count. So you can check if an argument was provided to your program by checking the value of argc.

Keep in mind, though, that the first value in argv is the executable name, so if you want to check that a argument was passed to your program you should have a check like:

if (argc >= 2) {
  ... do stuff ...
}
1

In your case you just should check the value of argc, as it holds the amount of parameters which are parsed to argv.

2
  • I don't understand your first line. Can you please clarify what you mean by "checking stder used as descriptor"?
    – BoBTFish
    Sep 13, 2013 at 7:39
  • My fault I mixed something sorry
    – dhein
    Sep 13, 2013 at 7:46
0

You should check argc as in:

const  string FileName= (argc < 2)?string():argv[1];

As for your specific question, you catch exceptions by means of a try/catch block as in

try{
exceptionThrowingOperation();
}
catch( ThrownExceptionType& e ){
exceptionHandling(e);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.