B
B
BestDirectolog2016-05-07 15:12:45
ruby
BestDirectolog, 2016-05-07 15:12:45

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

As it stands, ruby ​​(2.0 and 2.3) throws an ArgumentError but does not handle the rescue script.
If in the last test with an error, where one argument instead of three, activate the commented out code, then the exception will be processed, but this option is not interesting to me. If similar code is written in the initialize method, then it will not handle ArgumentError. Please explain how to make it work there, or at least why it does not work there?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zaporozhchenko Oleg, 2016-05-08
@c3gdlk

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 question

Ask a Question

731 491 924 answers to any question