例外処理

#例外サンプル
#	実行時引数にとったファイル名から、行数・単語数・文字数 を出力するプログラム

ltotal = 0	#行数
wtotal = 0	#単語数
ctotal = 0	#文字数

begin

	if ARGV.size > 3
		raise 'ファイル数が多すぎます。'	#例外の発生
	end

	ARGV.each{|file|
			input = open(file)	#ファイルオープン
			l = 0
			w = 0
			c = 0
			while line = input.gets  #1行ずつ読み込む
				l += 1
				c += line.size	#行の文字数
				line.sub!(/^\s/, '')   #行頭の空白を削除
				ary = line.split(/\s/) #splitも正規表現が使用可能?
				w += ary.size	#aryの要素数
			end
			
			input.close
			
			printf("%8d %8d %8d %s\r\n", l, w, c, file)
			ltotal += l
			wtotal += w
			ctotal += c

	}
	
	printf("%8d %8d %8d \r\n", ltotal, wtotal, ctotal)
	
rescue => ex
	print ex.message, "\r\n"
ensure
        print '処理が完了しました。'  #Finally
end