Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNicholas Olsen
Front End Web Development Techdegree Student 19,342 PointsInside of a protected method, how can you determine if it is being called inappropriately?
The Extra Credit for the Methods series in the Ruby Foundations course is this:
Now that we know the differences between the different kinds of methods, try writing a program with a protected method. Have that method raise a specific custom error if it's called inappropriately.
One thing I've tried is creating a custom error by inheriting from StandardError (or whatever) and then catching NoMethodError within a protected method and just raising my custom error. Like this:
class CustomError < StandardError
end
class MyClass
protected
def my_protected_method
begin
# ...
rescue NoMethodError
raise CustomError.new("Custom Error Message")
end
end
end
Unfortunately this doesn't work. I'm assuming because NoMethodError is thrown before any of the code inside the method gets executed. So, I think I can only catch a NoMethodError if I do so outside of the protected method like this:
begin
class_instance.my_protected_method
rescue NoMethodError
raise CustomError.new("Custom Error Message")
end
But of course, that does not fulfill the requirements of the assignment, which says:
...try writing a program with a protected method. Have that method raise a specific custom error if it's called inappropriately.
So, this way seems to be a dead end. How can I tell within a protected method if that method is being called inappropriately? The videos do not go over this, so I've had to look elsewhere.