How to check if operation returns an error

Hi all, I started learning ruby two weeks ago and I’m loving it. I’m
coding some date/time program to practice at the moment and I hit a
wall. I need a way to ask ruby whether or not a certain operation will
return an error. (I’ve tried google, I’ve searched this forum, the
manuals and IRC but to no avail, so I’m turning to you guys)

I don’t think the code is necessary since it’s probably a really easy
thing such as “.isitanerror” or whatever but here it is anyway.

To put you in context, before this, the program checks that all the
input was integers and well formated and then inputs the whole thing
into an array called “thedate”. Now I want to check if the array of
integers is a date or not (i.e. if someone enters ‘99’ in the ‘hour’
slot I want the program to know it’s not correct.) When I enter a real
date it works, when I enter malformated gibberish the code before
catches it but if I enter well formated “not date” numbers, the last
line before the “end” returns an error - so again, what I want to do is
to test wether or not that last line will return an error without
running it and breaking the program.

if problems != true
dateformated = thedate[0].to_s + ‘-’ + thedate[1].to_s + ‘-’ +
thedate[2].to_s + ‘T’ + thedate[3].to_s + ‘:’ + thedate[4].to_s + ‘:’ +

birthindate = DateTime.parse(dateformated)

thing such as “.isitanerror” or whatever but here it is anyway.
running it and breaking the program.
You can’t. You can, however, catch the error when it occurs:

irb(main):006:0> begin
irb(main):007:1* DateTime.parse ‘blah’
irb(main):008:1> rescue
irb(main):009:1> puts ‘learn to write a date fool!’
irb(main):010:1> end
learn to write a date fool!
=> nil

Have a look at the exceptions section here:

Thank you, it works perfectly!

Although not in the format I was expecting it, it’s exactly what I was
looking for.

begin … rescue way is similar to Java’s try…catch, and it is