提出MysqlError;提出Mysql :: Error两个工作,这是怎么发生的?

时间:2009-11-11 19:43:42

标签: mysql ruby exception gem

问候,

我正在研究mysql异常,我遇到了这个有趣的问题,其中一个引发的异常响应了两个不同的异常名称。这是怎么发生的?

-daniel

#!/usr/bin/env ruby

require 'rubygems'
require 'mysql'
require 'yaml'
require 'pp'

$config = YAML.load_file 'database.yml'

class ExceptionPrinter 

  def self.print msg, e
    puts msg
    pp e
  end

end

# sample connect: dbh = Mysql.real_connect $config['database']['host'], $config['database']['user'], $config['database']['password'], $config['database']['db'], $config['database']['port']

# test 1 - what class is thrown?

begin

  puts "Starting test - MysqlError"
  dbh = Mysql.real_connect $config['database']['host'], $config['database']['user'], $config['database']['password'], $config['database']['db']
  puts "Error: Code did not throw exception"

rescue MysqlError => e # MysqlError is not a valid exception catch

  ExceptionPrinter.print "MysqlError", e

rescue Exception => e

  ExceptionPrinter.print "Exception class", e

end

# test 2 - What class is thrown?

begin

  puts "Starting test - Mysql::Error"
  dbh = Mysql.real_connect $config['database']['host'], $config['database']['user'], $config['database']['password'], $config['database']['db']
  puts "Error: Code did not throw exception"

rescue Mysql::Error => e

  ExceptionPrinter.print "Mysql::Error", e

rescue Exception => e

  ExceptionPrinter.print "Exception class", e

end

- 输出

开始测试 - MysqlError 了MySqlError

开始测试 - Mysql ::错误 MySQL的::错误

1 个答案:

答案 0 :(得分:1)

看起来一个只是另一个的别名:

Mysql::Error
# => Mysql::Error
MysqlError
# => Mysql::Error

基于此,我期待MySQL gem中的某个地方有这样的一行:

class Mysql
  MysqlError = Mysql::Error
end

这意味着MysqlError是一个定义为类Mysql :: Error。

的常量