Basic Ruby / Exceptions
Visitors to VTC.com will be able to view all introductory videos for each training course.
Free Trial Members will gain access to first three chapters for each training course.
Full Access Members have full access to VTC.com’s entire library of video tutorials.
Learn More
Subtitles of the Movie
In this video we're going to look at exceptions in Ruby. Now, exceptions are when we get errors. If I go ahead and load this guy up right here, it's just a function that divides X by Y times itself, so Y squared. So let's start IRB and load 0908. So we have our definition. Now I can call that function and give it some values. Let's try that. It gives us eight. So 34 divided by four, it's integer math, so it's going to round it off because these are showing up as integers. Now, let's put in, instead of two, let's put in a zero. Now, we're dividing by zero. That's never good. We get that error and it crashes out on us. What if we wanted to catch that error? Well, I need to add some code in here. I already have some of this set up here. So what I've added is essentially this part right here and what I'm telling Ruby to do is if it detects a zero division error, which is a standard error message and there's a whole bunch of them and you can look in some of the resources I've mentioned in the resource video, uh, you'll see lists of, of these errors that are available out there. Then you're going to catch it and you can do something based on that error. Now, the easiest way to deal with this is enclose this whole structure where you want to catch that error in this begin and end kind of structure here just to give it a place for where you're looking for that error. Now, if I save this out and reload, now let's call that with zero. You're going to see my error message comes up. And this gives me the ability, there's some other tools in Ruby that will look at other videos to actually recover from this if you want, where, like, we have something here we could just print out exactly what we did, divide by zero, enter another number instead of your program actually crashing out and quitting. You can actually deal with the error and keep moving along or ask the user for something else or redo your calculation or whatever. So it's a pretty straightforward way. It's pretty similar to how other exceptions are done in other languages. So that's just a really basic look at exceptions in Ruby.
Tutorial Information
| Course: | Programming With Ruby |
| Author: | Al Anderson |
| SKU: | 33788 |
| ISBN: | 1-934743-01-1 |
| Release Date: | 2007-08-21 |
| Duration: | 8.5 hrs / 113 lessons |
| Work Files: |
Yes |
| Captions: | For Online University members only |
| Compatibility: |
Vista/XP/2000, OS X, Linux QuickTime 7, Flash 8 |
VTC Sign up & Benefits
- Unlimited Access
- 98,729 Video Tutorials (23,265 free)
- Video Available as Flash or QuickTime
- Over 1026 Courses
- $30 for One Month Access
- Multi-User Discounts Available
United States 