Answer the question
In order to leave comments, you need to log in
How to catch an exception in the initialization block?
I'm trying to deal with the topic of exceptions in ruby and somehow I can't find a clear answer to my problem: I can't make it so that the absence of arguments when creating the Train class is intercepted and processed by the rescue command in the initialize method.
class Train
attr_reader :speed, :wagons, :train_type, :train_rout, :current_station, :name
NAMEPATTERN = /[а-яА-Яa-zA-Z0-9]{3}-?[а-яА-Яa-zA-Z0-9]{2}/
def initialize(wagons, train_type, name)
@wagons = wagons
@train_type = train_type
@name = name
valid? #подключаем метод который должен обработать отсутствие аргументов
initialize_super # подключаем метод из счетчика instance_counter подсчитывающий экземпляры класса
@speed = 0
puts "\nTrain created! It's #{@train_type} train, with #{@wagons} wagons, with name #{@name}."
end
def valid! # метод отвечающий за выброс ошибок
raise ArgumentError, 'Wagon is nil' if wagons.nil? # в случае отсутствия аргумента выбрасываем ошибку, именно эти три помеченные ArgumentError не выбрасываются
raise ArgumentError, 'Train_type is nil' if train_type.nil?
raise ArgumentError, 'name is nil' if name.nil?
raise RuntimeError, 'Wrong train name' if name !~ NAMEPATTERN
true
end
def valid?
valid!
rescue RuntimeError
puts "\nWrong train name."
false
rescue ArgumentError
puts "\nTrain does not created! No arguments."
false
end
end
puts "Тестируем без ошибок"
train7 = Train.new(13, "Passenger's", '888-88')
puts "Тестируем с ошибкой"
#begin
train8 = Train.new(44)
#rescue ArgumentError
#puts "\nTrain does not created! No arguments."
#end
Answer the question
In order to leave comments, you need to log in
he doesn't work there because ruby doesn't go inside. You don't have the same number of arguments. You can do something like this
def initialize(*args)
if args.size == 3
wagons, train_type, name = args
#main logic here
else
#handle error
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question