# Problems with catching an exception

**URL:** <https://www.ruby-forum.com/t/problems-with-catching-an-exception/117177>\
**Category:** Ruby\
**Created:** [October 14, 2007, 12:09pm UTC](https://www.ruby-forum.com/t/problems-with-catching-an-exception/117177 "2007-10-14T12:09:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [October 14, 2007, 12:09pm UTC](https://www.ruby-forum.com/t/problems-with-catching-an-exception/117177/1 "2007-10-14T12:09:10Z")

</div>

Hi all

I’m having some basic newbie problem with catching an exception.  
The following code does not seem to catch the URI::InvalidURIError,  
because the line record.errors.add… is never executed.

def validates\_url\_form\_of(\*attr\_names)  
attr\_name = attr\_names.first.to\_s

```
validates_each(attr_name) do |record, attr_name, value|
  uri = URI.parse(record.send(attr_name.to_sym))
  if uri.class != URI::HTTP
    record.errors.add(attr_name, 'Only HTTP protocol addresses can

```

be used’)  
end  
end  
rescue URI::InvalidURIError  
errors.add(attr\_name, ‘The format of the url is not valid.’)  
end

I tried it the following way:

def validates\_url\_form\_of(\*attr\_names)  
attr\_name = attr\_names.first.to\_s

```
validates_each(attr_name) do |record, attr_name, value|
  uri = URI.parse(record.send(attr_name.to_sym))
  if uri.class != URI::HTTP
    record.errors.add(attr_name, 'Only HTTP protocol addresses can

```

be used’)  
end  
rescue URI::InvalidURIError  
errors.add(attr\_name, ‘The format of the url is not valid.’)  
end  
end  
end

But this gives me a syntax error.

What am I missing?

Thanks a lot.  
Josh

---

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [October 14, 2007, 12:24pm UTC](https://www.ruby-forum.com/t/problems-with-catching-an-exception/117177/2 "2007-10-14T12:24:40Z")

</div>

“rescue” clauses should be either part of a def … end construct like  
this

def my\_method  
…  
rescue URI::InvalidURIError  
end

or – and it is your case here – in a begin … end construct like this

begin  
`
rescue URI::InvalidURIError
end`

---

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [October 14, 2007, 1:56pm UTC](https://www.ruby-forum.com/t/problems-with-catching-an-exception/117177/3 "2007-10-14T13:56:55Z")

</div>

Thank you. 🙂
