2009-11-11 40 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的常量。