异常类如何获取引发它的对象?

时间:2013-08-31 04:40:32

标签: ruby exception binding

我希望我的一个异常类能够获取在其上下文中引发异常的对象。例如,在半伪代码中

class Foo
  def zorch!
    raise MyException.new("d'oh!")
  end
end

c = Foo.new
c.zorch!

我希望MyException#initialize能够获取对象c

这可以使用self.send(:binding)方法中的#initialize以某种方式完成,但我还没弄明白:

Kernel.eval('self', self.send(:binding)).class.name
=> MyException   # *not* 'Foo'

这是有道理的,因为MyException尚未完全实例化,self.send(:binding)引用当前上下文而不是调用者。

那么如何访问调用者的上下文/绑定?

2 个答案:

答案 0 :(得分:2)

class MyException < StandardError
  attr_reader :obj
  def initialize obj, *args; super(*args); @obj = obj end
end

class Foo
  def zorch!
    raise MyException.new(self, "d'oh!")
  end
end

c = Foo.new
begin
  c.zorch!
rescue => e
  puts e.obj
end
# => #<Foo:0x007fdd4a474da0>

答案 1 :(得分:1)

来自http://docs.honeybadger.io/ruby/exceptions/extending-ruby-exceptions.html的代码是您可以获得的最佳代码:

<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/png" href="./images/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./images/favicon-16x16.png" sizes="16x16" />
<title>MLB: Major League Baseball</title>
<link href="css folder/MLBstylesheet.css" rel="stylesheet" type="text/css"/>
</head> 
<body>
<div id="container">
<div id="titel">    

<img class="MLBTitel"  src="./images/MLBtitel.jpg" alt="MLBTitel" >
<div id="titeltekst">
MAJOR LEAGUE BASEBALL
<br>    
</div>

<nav>
<ul>
    <li><a class= "menu" href="index.html">Home</a></li>
    <li><a class= "menu" href="spelers.php">Spelers</a></li>
    <li><a id = "active" class= "menu" href="teams.php">Teams</a></li>
    <li><a class= "menu" href="wedstrijden.html">Wedstrijden</a></li>
    <li><a class= "menu" href="contact.html">Contact</a></li>
</ul>
</nav>

<br><br>        
</div>
<div id="teamtabel">
<?php
$servername = "localhost";
$username = "id1419279_root";
$password = "*******";
$dbname = "id1419279_mlb";

// Create connection
$conn = new mysqli($localhost, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM teams";
$result = $conn->query($sql);

$dropdownlist = '';

while($row = mysqli_fetch_array($result)) {

$teamnaam = $row['teamnaam'];

$dropdownlist .="<option value='" . $teamnaam . "'>" . $teamnaam . "</option>";

}

if(isset($dropdownlist)){

    echo "<select name='naamteam'>";

    echo $dropdownlist;

    echo "</select>";
}
?>

</div>
</div>
</body>
</html>

它适用于大多数例外,但不适用于MRI内部提出的内部例外情况。