gpt4 book ai didi

mysql - 引发 MysqlError; raise Mysql::Error 都有效,这是怎么发生的?

转载 作者:行者123 更新时间:2023-11-30 21:23:13 25 4
gpt4 key购买 nike

问候,

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

-- 输出

开始测试 - MysqlErrorMysql错误

开始测试 - Mysql::ErrorMysql::错误

最佳答案

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

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

基于此,我期望在 MySQL gem 的某处有这样一行:

class Mysql
MysqlError = Mysql::Error
end

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

关于mysql - 引发 MysqlError; raise Mysql::Error 都有效,这是怎么发生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1717572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com