最近开始用Ruby进行编程,并且正在寻找异常处理。
想知道是否在C#中ensure的Ruby等价物finally?比如:
file = File.open(""myFile.txt"", ""w"")
begin
file << ""#{content} \n""
rescue
#handle the error here
ensure
file.close unless file.nil?
end
或者应该这样做?
#store the file
file = Fi
我正在尝试构建一个应用程序,该应用程序定期扫描各个Git分支上的提交历史,并报告作者的报告以及提交消息的各种详细信息。为此,我已经开始使用。对于访问提交本身来说,这是很棒的,但是我在试图更新存储库时遇到了一个障碍。
每次任务运行时,我都需要从远程存储库获得最新的更改。我的理解是,我需要签出跟踪相关远程分支的本地分支,然后执行提取或拉动操作。我试图在我的应用程序中这样做如下:
// Get the branch
var localBranch = repo.Branches[localbranchName];
// Switch to this branch
if (!localBranch.
我试图理解Ruby中的异常,但我有点困惑。我使用的教程说,如果发生了与救援语句标识的任何异常不匹配的异常,则可以使用“occurs”来捕获它:
begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Other exceptions
ensure
# Always will be executed
end
但是,我在后面的教程“救援”中也看到了毫无例外地使用:
begin
file = open("/unexistant_file")
MSDN告诉我们,当你在一个不存在的文件上调用"File.Delete( path );“时,会产生一个异常。
在执行删除操作之前,调用delete方法并使用try/catch块来避免错误或验证文件的存在会更有效吗?
我倾向于认为最好避免try/catch块。当你知道如何检查错误时,为什么要让它发生呢?
无论如何,下面是一些示例代码:
// Option 1: Just delete the file and ignore any exceptions
/// <summary>
/// Remove the files from the local server if
我试图使用类似于下面类的异常,但是当我调用kivetel方法时,程序总是失败的。我认为它只会调用重试部分,而不是满足后条件。但在违反"y_above_zero“后,它就失败了。
class
KEYWORDS
create
make
feature
y:INTEGER
make
do
end
kivetel
do
ensure
y__above_zero: y > 0
rescue
y := 20
retry
end
end
我从了解到,对于在某个块中可能发生的多个异常,可以使用相同的处理程序,例如:
[ do some work ]
on: ZeroDivide, Warning
do: [ :ex | what you want ]
在同一文档中,有一个使用ensure确保代码始终被执行的示例(尽管有任何例外):
[ doSomething ] ensure: [ alwaysExecuteThis ]
不过,我想要的是:
[ do some work ]
on: ZeroDivide
do: [ :zeroDivide | handle it ]
on: Warning
do: [ :warning | ha
我刚刚安装了django-sentry,它可以很好地捕获异常。但是,由于某些原因,对logger.warning和logger.error的调用并未保存到前哨。
哨兵实现:
import logging
from sentry.client.handlers import SentryHandler
logger = logging.getLogger()
# ensure we havent already registered the handler
if SentryHandler not in map(lambda x: x.__class__, logger.handlers):
假设我在Ruby中打开一个文件,如下所示:
f = File.open('diagram.txt', 'r')
现在,为了关闭和删除该文件,我有以下代码:
begin
f = File.open('diagram.txt', 'r')
ensure
if !f.nil? && File.exist?(f)
f.close unless f.closed?
File.delete(f)
end
end
我发现这段代码太复杂了,如果f已经关闭,File.exist?(f)就会失败。那么,避
根据第164页。
如果begin语句不传播异常,则该语句的值为--在begin、rescue或else子句中计算的最后一个表达式的值。
但是,我发现这种行为与begin块以及else子句和ensure子句一致。
下面是示例代码:
def fact (n)
raise "bad argument" if n.to_i < 1
end
value = begin
fact (1)
rescue RuntimeError => e
p e.message
else
p "I am in the else statement"
en
我得到了以下错误:
Test method: BootStrapperTest.Can_Create_Alert_Management_Object threw exception: Ninject.ActivationException:
Error activating IAlertManagement No matching bindings are available, and the type is not self-bindable.
Activation path:
1) Request for IAlertManagement
Suggestions:
当前我正在工作或使用msmq私有队列,我需要将其更改为公共队列。我发现,我只需要更改端点地址
address="net.msmq://132.186.201.193/private/IEventQueue"
至
address="net.msmq://132.186.201.193/public/IEventQueue"
然而,这是不起作用的,我面临的异常是
There was an error opening the queue. Ensure that MSMQ is installed and running, the queue exists and
我的Rails应用程序中有以下代码:
def test
begin
puts 'a'
authenticate_user!
puts 'b'
rescue Exception => e
puts 'c'
ensure
puts 'd'
end
puts 'e'
end
其中:
test是Rails中的一个控制器
authenticate_user!是devise库中的一个函数。
我注意到我写了“尝试”--除了像下面这样的条款。这样做的主要原因是要编写更少的代码。
class Synchronizer(object):
# ...
def _assert_dir(self, dirname, argname, argnum):
""" *Private*. Raises OSError if the passed string does not point
to an existing directory on the file-system. """
我刚刚创建了一个具有超薄框架的API应用程序,最初,在我的代码中,我使用依赖容器来处理抛出的所有异常,代码如下所示。
//Add container to handle all exceptions/errors, fail safe and return json
$container['errorHandler'] = function ($container) {
return function ($request, $response, $exception) use ($container) {
//Format of exception to
try{
RecordMetadata d = producer.send(message).get()
if(d.hasoffset()){
//only way to ensure kafka was sent??
}}
catch (Exception e){
//or does this alone guarentee the message was sent
}
单独捕获异常是否确保消息被发送,或者是否需要一些if语句检查?
我想选择路径,所以我使用了Folderbrowser dialog.But,它在"DialogResult result =fbd.ShowDialog();“行显示异常,异常是
Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a de
我有一个自定义的数据源,我们称它为SQSDatasource。一般来说,它在find()、save()甚至delete()上都运行得很好。
class SQSDatasource extends DataSource {
public function delete(Model $Model, $conditions = null) {
// Deliberate break point to ensure that this function is being called
print_r($conditions);
exit();