2009-11-11 38 views
1

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

我正在处理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

它看起来像一个仅仅是一个别名,其他:

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

此基础上,我期待的是,在MySQL的宝石某处有这样一行:

class Mysql 
    MysqlError = Mysql::Error 
end 

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