我确信这个概念已经出现过,但我找不到一个好的,简单的答案.使用try/finally是一种处理多个返回函数的坏方法吗?比如我有
try:
if x:
return update(1)
else:
return update(2)
finally:
notifyUpdated()
这似乎比在临时变量中存储update()命令并返回它更好.
可能重复:
最后块没有运行?
我有一个关于c#中finally块的问题.我写了一个小示例代码:
public class MyType
{
public void foo()
{
try
{
Console.WriteLine("Throw NullReferenceException?");
string s = Console.ReadLine();
if (s == "Y")
throw new NullReferenceException();
else
throw new ArgumentException();
}
catch (NullReferenceException)
{
Console.WriteLine("NullReferenceException was caught!");
}
finally
{
Console.WriteLine("finally block");
}
}
}
class Program
{
static void Main(string[] args)
{
MyType t = new MyType();
t.foo();
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,最后阻塞假设确定性地运行,无论是否抛出异常.现在,如果用户输入"Y" - 抛出NullReferenceException,则执行移动到catch时钟,然后移动到finally块,如我所料.但如果输入是其他东西 - 抛出ArgumentException.没有合适的catch块来捕获这个异常,所以我认为执行应该移动finally块 - 但它没有.有人可以解释一下为什么?
感谢大家 :)
我有一个System.Timers.Timer定时器,它AutoReset被设置为false.我使用a try/finally来确保Start它的结束时callback的计时器(我使用计时器这种方式来防止重复callback执行).码:
// inside timer call back
try
{
// Do something
}
finally
{
timer.Start(); // Is this line always executed?
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如果执行线程是什么会发生什么Aborted?该finally部分是否仍然执行或者没有线程来运行该部分?
你是如何在smalltalk中实现try-catch-finally成语的?我看到有on:do:和ensure:,但没有on:do:ensure:.我肯定错过了什么.
所以我有一个try/finally块.我需要在finally块中执行许多方法.但是,这些方法中的每一个都可以抛出异常.有没有办法确保在没有嵌套的finally块的情况下调用(或尝试)所有这些方法?
这就是我现在所做的,这非常难看:
protected void verifyTable() throws IOException {
Configuration configuration = HBaseConfiguration.create();
HTable hTable = null;
try {
hTable = new HTable(configuration, segmentMatchTableName);
//...
//various business logic here
//...
} finally {
try {
try {
if(hTable!=null) {
hTable.close(); //This can throw an IOException
}
} finally {
try {
generalTableHelper.deleteTable(configuration, segmentMatchTableName); //This can throw an IOException
} finally {
try {
generalTableHelper.deleteTable(configuration, wordMatchTableName); //This can throw an IOException
} finally {
generalTableHelper.deleteTable(configuration, haplotypeTableName); //This can throw an IOException
} …Run Code Online (Sandbox Code Playgroud) java exception-handling exception try-catch-finally try-finally
我已经搜索了一些答案,但找不到,因此我将此作为一个新问题提出来.try-catch中的catch方法.这是一种方法吗?,它将Exception类型的对象作为参数.但如果它是一种方法,
谁调用此方法以及调用此方法的对象?
你不能正常在另一个方法定义中写一个方法定义.所以如果它是一个方法,我怎么能在另一个方法中写入catch?
如果它不是一种方法,那么它是什么?
public void foo() {
try { ;
} catch (Exception ex) {
; // this is catch method body
}
}
Run Code Online (Sandbox Code Playgroud)上面的代码意味着catch方法体在另一个方法foo()的体内.
在Java中,不建议finally在try-chatch块的section中抛出异常,因为它会隐藏任何throwable在tryor catch块中抛出的未处理的传播。blocker根据默认的声纳配置文件,此做法违反了液位。
声纳错误:从此finally块中删除此throw语句。
请考虑以下代码段。
例如:在finally块内关闭输入流,并在关闭流时处理可能的异常。
public void upload(File file) {
ChannelSftp c = (ChannelSftp) channel;
BufferedInputStream bis = new BufferedInputStream(file.toInputStream());
try {
String uploadLocation = Files.simplifyPath(this.fileLocation + "/" + file.getName());
c.put(bis, uploadLocation);
} catch (SftpException e) {
throw new IllegalTargetException("Error occurred while uploading " + e.getMessage());
} finally {
try {
bis.close();
} catch (IOException e) {
throw new UnsupportedOperationException("Exception occurred while closing Input stream " + e.getMessage());
} …Run Code Online (Sandbox Code Playgroud) 我遇到了这个问题,我无法理解它给出的输出的原因.
该计划是:
public static String method(){
String s = new String();
try
{
s = "return value from try block";
return s;
}
catch (Exception e)
{
s = s + "return value from catch block";
return s;
}
finally
{
s = s + "return value from finally block";
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
从try块返回值
现在,我调试它和值s在return s中陈述try阻滞return value from try block,return value from catch block后returned from finally block.
输出仍然是: …
到目前为止,C++(不幸的是)不支持finally语句的子句try.这导致了对如何释放资源的猜测.在互联网上研究了这个问题之后,虽然我找到了一些解决方案,但我并没有明白他们的表现(如果表现并不重要,我会使用Java).所以我不得不做基准测试.
选项是:
CodeProjectfinally提出的基于Functor的类.它很强大,但很慢.并且反汇编表明外部函数局部变量被非常低效地捕获:逐个推送到堆栈,而不是仅仅将帧指针传递给内部(lambda)函数.
RAII:堆栈上的手动清洁器对象:缺点是手动键入并为每个使用的位置定制它.另一个缺点是需要将资源释放所需的所有变量复制到其中.
MSVC++特定__try/ __finally声明.缺点是它显然不便携.
我创建了这个小基准来比较这些方法的运行时性能:
#include <chrono>
#include <functional>
#include <cstdio>
class Finally1 {
std::function<void(void)> _functor;
public:
Finally1(const std::function<void(void)> &functor) : _functor(functor) {}
~Finally1() {
_functor();
}
};
void BenchmarkFunctor() {
volatile int64_t var = 0;
const int64_t nIterations = 234567890;
auto start = std::chrono::high_resolution_clock::now();
for (int64_t i = 0; i < nIterations; i++) {
Finally1 doFinally([&] {
var++;
});
}
auto elapsed = std::chrono::high_resolution_clock::now() - start;
double …Run Code Online (Sandbox Code Playgroud) 在新的第三版Effective Java中,Joshua Bloch提到了Java Puzzlers的一段代码(它是关于在try-finally中关闭资源):
对于初学者来说,我在Java Puzzlers的第88页上弄错了,多年来没有人注意到.事实上,2007年Java库中close方法的三分之二使用是错误的.
但我不确定哪个部分错了?
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
// There is nothing we can do if close fails
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
// Again, there is nothing we can do if close fails
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是此代码的新版本:
try {
OutputStream out = new FileOutputStream(dst);
try {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while …Run Code Online (Sandbox Code Playgroud) java ×5
try-finally ×3
c# ×2
try-catch ×2
c++ ×1
exception ×1
finally ×1
flow-control ×1
performance ×1
python ×1
raii ×1
smalltalk ×1
sonarqube ×1
timer ×1