views:

35

answers:

1

Greetings,

I was working on mysql exceptions and I came across this interesting issue, in which a raised exception is responding to two different exception names. How did this happen?

-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

-- Output

Starting test - MysqlError MysqlError

Starting test - Mysql::Error Mysql::Error

+1  A: 

It looks like one is just an alias to the other:

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

Based on that, I'm expecting that somewhere in the MySQL gem there's a line like this:

class Mysql
  MysqlError = Mysql::Error
end

This implies MysqlError is a constant defined as the class Mysql::Error.

tadman