# OptionParser error handling (InvalidArgument)

**URL:** <https://www.ruby-forum.com/t/optionparser-error-handling-invalidargument/221895>\
**Category:** Ruby\
**Created:** [August 3, 2012, 6:04pm UTC](https://www.ruby-forum.com/t/optionparser-error-handling-invalidargument/221895 "2012-08-03T18:04:27Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![aris](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/258eb7/32.png) [@aris](https://www.ruby-forum.com/u/aris)\
**Post date:** [August 3, 2012, 6:04pm UTC](https://www.ruby-forum.com/t/optionparser-error-handling-invalidargument/221895/1 "2012-08-03T18:04:27Z")

</div>

Hello,

I’d like to make an OptParser error look a bit more explanatory. I tried  
to deal with it outside OpiontParser like this:

* * *

# check if options[:no] is interger

## if options[:no] begin $no = Integer(options[:no]) rescue ArgumentError puts “#{$no} is not an Integer!” else true end else $no = 0 end

but didn’t work. The error I get from cli is:

f2bread.rb:483:in `': invalid argument: -s duck  
(OptionParser::InvalidArgument)

Apparently I need to somehow handle this from within OptionParser. Any  
ideas on how to proceed? I found this post[1] online which explains  
what I want but I couldn’t figure how exactly it works. So some actual  
codes with a sort of explanation of where _exactly_ sits on the program  
(outside or inside “OptionParser.new” class?).

## The relevant OptionParser lines, where is specified that ‘-n’ accepts Integers, are:

## opts.on(‘-n’, ‘–no N’, Integer, ‘Number of top entries to be displayed. By default all entries are displayed.’) do |no| options[:no] = no end

[1] [http://blog.segment7.net/2008/01/05/optionparser-argument-casting](http://blog.segment7.net/2008/01/05/optionparser-argument-casting)

Best Regards,

Panagiotis A.

---

<div class="post-metadata">

**Author:** ![atma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/858c86/32.png) [@atma](https://www.ruby-forum.com/u/atma)\
**Post date:** [August 3, 2012, 6:58pm UTC](https://www.ruby-forum.com/t/optionparser-error-handling-invalidargument/221895/2 "2012-08-03T18:58:14Z")

</div>

What do you mean, more explanatory?

---

<div class="post-metadata">

**Author:** ![atma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/858c86/32.png) [@atma](https://www.ruby-forum.com/u/atma)\
**Post date:** [August 3, 2012, 8:22pm UTC](https://www.ruby-forum.com/t/optionparser-error-handling-invalidargument/221895/3 "2012-08-03T20:22:59Z")

</div>

It is not clear to me what your problem is.

Slightly adapted from the post cited by you:

* * *

require ‘optparse’

options = {}

opts = OptionParser.new do |opts|

# Cast ‘no’ argument to an Integer.

opts.on(‘-n’, ‘–no N’, Integer, ‘Number of…’) do |no|  
options[:no] = no  
end  
end

opts.parse!(ARGV)

## p options

results (as it should) in

$ ruby optparse.rb -n 34  
{:no=\>34}

$ ruby optparse.rb -n duck  
optparse.rb:12:in `': invalid argument: -n duck  
(OptionParser::InvalidArgument)

Am 03.08.2012 18:03, schrieb Panagiotis A.:

> ```
> end
> 
> ```
> 
> else  
> $no = 0  
> end

This is not necessary, since the option value has already been  
cast to an integer, or an exception has been raised.

Btw, you should not use global variables.

> ```
> options[:no] = no
> end
> 
> ```
> 
> * * *

actually, it _did_ work. “duck” is not an integer,  
so an exception is raised.

---

<div class="post-metadata">

**Author:** ![atma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/858c86/32.png) [@atma](https://www.ruby-forum.com/u/atma)\
**Post date:** [August 4, 2012, 1:25am UTC](https://www.ruby-forum.com/t/optionparser-error-handling-invalidargument/221895/4 "2012-08-04T01:25:08Z")

</div>

Hello

On 3 Αυγ 2012, at 19:56 , Jam [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> What do you mean, more explanatory?

I want to print an output similar to the one after the rescue keyword  
below. Just that.

> > ```
> > begin
> > 
> > ```
> > 
> > ## but didn’t work. The error I get from cli is:
> > 
> > More info: [http://about.me/atmosx](http://about.me/atmosx)
> > 
> > The wise man said: “Never argue with an idiot, he brings you down to his level  
> > and beat you with experience.”

Panagiotis A.

---

<div class="post-metadata">

**Author:** ![atma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/858c86/32.png) [@atma](https://www.ruby-forum.com/u/atma)\
**Post date:** [August 3, 2012, 8:51pm UTC](https://www.ruby-forum.com/t/optionparser-error-handling-invalidargument/221895/5 "2012-08-03T20:51:37Z")

</div>

Maybe you were looking for something like this:

* * *

require ‘optparse’

options = {  
:no =\> 0  
}

opts = OptionParser.new do |opts|  
opts.on(‘-n’, ‘–no N’,  
“Number of… Default value: #{options[:no]}”) do |no|  
if /\A[+]?\d+\Z/ === no # nonnegative integer?  
options[:no] = no  
else  
warn “#{no} is not a nonnegative integer, using default value”  
end  
end  
end

opts.parse!(ARGV)

## p options

$ ruby optparse.rb -n -5  
-5 is not a nonnegative integer, using default value  
{:no=\>0}

$ ruby optparse.rb -n 3  
{:no=\>“3”}

Am 03.08.2012 18:03, schrieb Panagiotis A.:

> ```
> end
> 
> ```
> 
> ## else $no = 0 end

Personally, I do not like provoking an exception only to  
test whether no is an integer.  
Also, the ‘else’ part from begin-rescue-else is useless.

---

<div class="post-metadata">

**Author:** ![atma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/858c86/32.png) [@atma](https://www.ruby-forum.com/u/atma)\
**Post date:** [August 4, 2012, 1:36am UTC](https://www.ruby-forum.com/t/optionparser-error-handling-invalidargument/221895/6 "2012-08-04T01:36:15Z")

</div>

Hello,

Thanks for the reply.

On 3 Αυγ 2012, at 21:21 , [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> It is not clear to me what your problem is.

I dislike the way the error is displayed. I’d like to print a message  
like the one after the ‘rescue’ keyword. Maybe it’s not a good practice  
though and I should leave it as is.

> options[:no] = no  
> $ ruby optparse.rb -n 34
> 
> > if options[:no]
> 
> This is not necessary, since the option value has already been  
> cast to an integer, or an exception has been raised.
> 
> Btw, you should not use global variables.

Why not?

> > ## opts.on(‘-n’, ‘–no N’, Integer, ‘Number of top entries to be displayed. By default all entries are displayed.’) do |no| options[:no] = no end
> 
> actually, it _did_ work. “duck” is not an integer,  
> so an exception is raised.

I just want to print a predefined error message. It seems more easy to  
read to me, although as I said above, it might not be a good practice  
and I’m not sure anymore if I should add it or no 😛 given the fact  
that you’re the second person pointing out that “it’s working as it  
should”.

> > [1] [http://blog.segment7.net/2008/01/05/optionparser-argument-casting](http://blog.segment7.net/2008/01/05/optionparser-argument-casting)
> 
> –  
> [https://github.com/stomar/](https://github.com/stomar/)

A bit off-topic now. In your next email you told me that you dislike  
raising an exception in order to identify an integer. A second approach  
I found online was using regexp. However this was the answer I got from  
a user at ‘stackoverflow’ which convinced that this is the right way to  
go in ruby:

"Sarah: you can use a Regex but in order to handle all the cases that  
Ruby does when parsing integers (negative numbers, hex, octal,  
underscores e.g. 1\_000\_000) it would be a very big Regex and easy to get  
wrong. Integer() is canonical because with Integer ()you know for sure  
that anything that Ruby considers an integer literal will be accepted,  
and everything else will be rejected. Duplicating what the language  
already gives you is arguably a worse code smell than using exceptions  
for control. – Avdi " from  
[http://stackoverflow.com/questions/1235863/test-if-a-string-is-basically-an-integer-in-quotes-using-ruby](http://stackoverflow.com/questions/1235863/test-if-a-string-is-basically-an-integer-in-quotes-using-ruby)

Best Regards

Panagiotis A.

---

<div class="post-metadata">

**Author:** ![atma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/858c86/32.png) [@atma](https://www.ruby-forum.com/u/atma)\
**Post date:** [August 4, 2012, 3:42pm UTC](https://www.ruby-forum.com/t/optionparser-error-handling-invalidargument/221895/7 "2012-08-04T15:42:08Z")

</div>

Am 04.08.2012 01:31, schrieb Panagiotis A.:

> A bit off-topic now. In your next email you told me that you dislike  
> raising an exception in order to identify an integer. A second  
> approach I found online was using regexp.

That’s what I did in my version, too.

> exceptions for control. – Avdi " from

[http://stackoverflow.com/questions/1235863/test-if-a-string-is-basically-an-integer-in-quotes-using-ruby](http://stackoverflow.com/questions/1235863/test-if-a-string-is-basically-an-integer-in-quotes-using-ruby)

Imo there is no “canonical” way that fits all use cases.

Here, in connection with command line arguments, I prefer  
using a regexp (probably as a second choice after using the Integer  
cast from optparse): I do not expect an octal integer as user input,  
the regexp is rather simple, and the approach is flexible.  
I can for example test for integers or for nonnegative integers, with

/\A[±]?\d+\Z/ === str or /\A[+]?\d+\Z/ === str

Partly a matter of taste.
