classifying exceptions

J

Joel VanderWerf

There are many places in my code that need to catch any error generated
by a network system call, but I don't want to catch everything that
inherits from SystemCallError. This is my current code:

ALL_NETWORK_ERRORS = [Errno::ECONNRESET, Errno::ECONNABORTED,
Errno::ECONNREFUSED, Errno::EPIPE, IOError, Errno::ETIMEDOUT]

ALL_NETWORK_ERRORS << Errno::EPROTO if defined?(Errno::EPROTO)
# this doesn't exist on mswin32

begin
raise Errno::ECONNREFUSED
rescue *ALL_NETWORK_ERRORS
puts "OK!"
end

Now, here's another option, but is there anything wrong with it?

module NetworkRaisable; end
class Errno::EPROTO; include NetworkRaisable; end
class Errno::ECONNREFUSED; include NetworkRaisable; end
# and so on

begin
raise Errno::ECONNREFUSED
rescue NetworkRaisable
puts "OK!"
end
 
N

nobuyoshi nakada

Hi,

At Thu, 15 Sep 2005 14:57:22 +0900,
Joel VanderWerf wrote in [ruby-talk:156196]:
Now, here's another option, but is there anything wrong with it?

module NetworkRaisable; end
class Errno::EPROTO; include NetworkRaisable; end
class Errno::ECONNREFUSED; include NetworkRaisable; end
# and so on

begin
raise Errno::ECONNREFUSED
rescue NetworkRaisable
puts "OK!"
end

Actually, an exception, to be caught, doesn't have to be
including target module always.

module NetworkRaisable
def self.===(ex)
case ex
when Errno::EPROTO, Errno::ECONNREFUSED: true
end
end
end
 
J

Joel VanderWerf

nobuyoshi said:
Hi,

At Thu, 15 Sep 2005 14:57:22 +0900,
Joel VanderWerf wrote in [ruby-talk:156196]:
Now, here's another option, but is there anything wrong with it?

module NetworkRaisable; end
class Errno::EPROTO; include NetworkRaisable; end
class Errno::ECONNREFUSED; include NetworkRaisable; end
# and so on

begin
raise Errno::ECONNREFUSED
rescue NetworkRaisable
puts "OK!"
end


Actually, an exception, to be caught, doesn't have to be
including target module always.

module NetworkRaisable
def self.===(ex)
case ex
when Errno::EPROTO, Errno::ECONNREFUSED: true
end
end
end

Thanks, that's better. I forgot rescue uses case-matching. And it avoids
modifying ruby built-in classes. (And NetworkRaisable doesn't even have
to be a module.)
 
N

nobu.nokada

Hi,

At Fri, 16 Sep 2005 01:31:37 +0900,
Joel VanderWerf wrote in [ruby-talk:156280]:
Thanks, that's better. I forgot rescue uses case-matching. And it avoids
modifying ruby built-in classes. (And NetworkRaisable doesn't even have
to be a module.)

Arguments to rescue must be modules.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top