新手问题 class 拒绝被 new

u4crella · November 07, 2019 · Last by ybintian replied at November 10, 2019 · 2093 hits

如何修改 class 的 initialize 方法,使得获取参数不符合要求的时候,无法在外部 new 这个 class 的实例? 如果这样做不可以,那么是要写个方法来检查并 new class 吗? 新手上路,感觉很多知识很乱且不知道在哪里查、怎么输关键字。

def initialize(number)
...
raise ArgumentError if number < 100
end

抛出异常,程序终止。或者捕获异常,处理错误继续执行

Reply to zhongsheng

raise Exception 可以,谢谢。

You need to Sign in before reply, if you don't have an account, please Sign up first.