问候,
我正在研究 mysql 异常,遇到了这个有趣的问题,其中引发的异常响应两个不同的异常名称。这怎么发生的?
-丹尼尔
#!/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::Error Mysql::Error