# "save! and rescure" or if-else

**URL:** <https://www.ruby-forum.com/t/save-and-rescure-or-if-else/138217>\
**Category:** Rails\
**Created:** [May 21, 2008, 5:15am UTC](https://www.ruby-forum.com/t/save-and-rescure-or-if-else/138217 "2008-05-21T05:15:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![T\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e0b2c6/32.png) [@T\_K](https://www.ruby-forum.com/u/T_K)\
**Post date:** [May 21, 2008, 5:15am UTC](https://www.ruby-forum.com/t/save-and-rescure-or-if-else/138217/1 "2008-05-21T05:15:07Z")

</div>

When browsing various projects, I noticed two ways to write a saving  
feature.

1. 

def create  
if @post.save  
flash[:notice] = “Success”  
redirect\_to :action =\> “index”  
else  
render :action =\> “new”  
end

1. 

def create  
@post.save!  
flash[:notice] = “Success”  
redirect\_to :action =\> “index”  
rescue  
render :action =\> "new  
end

Which is better? What’s the pros and cons for each usage?

-T

---

<div class="post-metadata">

**Author:** ![T\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e0b2c6/32.png) [@T\_K](https://www.ruby-forum.com/u/T_K)\
**Post date:** [May 21, 2008, 5:42am UTC](https://www.ruby-forum.com/t/save-and-rescure-or-if-else/138217/2 "2008-05-21T05:42:02Z")

</div>

> end  
> end
> 
> Which is better? What’s the pros and cons for each usage?

An advantage for 1 is that if you did say “x = 1 / 0” an error would be  
raised and you’d har about it. In 2 that error would be rescued and  
you’d  
never know you had a problem. Granted that’s a bogus example, but  
replace  
1 and 0 with variables and it can happen.

An advantage for 2 is that you’ll catch all the errors so if you really  
don’t want to handle them individually you can simplify your could.

That said, if going with option two, you may want to rescue the specific  
exception thrown when the save fails, and allow others to bubble up…

-philip

---

<div class="post-metadata">

**Author:** ![T\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e0b2c6/32.png) [@T\_K](https://www.ruby-forum.com/u/T_K)\
**Post date:** [May 21, 2008, 8:31am UTC](https://www.ruby-forum.com/t/save-and-rescure-or-if-else/138217/3 "2008-05-21T08:31:14Z")

</div>

On 21 May 2008, at 04:41, Philip H. wrote:

> > else  
> > rescue  
> > replace  
> > 1 and 0 with variables and it can happen.

Yup, an unqualified rescue can be a nasty thing. I’d also add that I  
like to think of exceptions as for exceptional things (weird errors, a  
database deadlock etc…) The user fat-fingering something isn’t  
something like that.

Fred
