因此,我开始使用 Java 8 流/lambda 表达式,并遇到了一些有趣的问题,我不太确定如何解决。所以我在这里请求你的帮助。
有问题的示例代码:
public void insertBlankPages(File inputFile, String outputFile, final int OFFSET) {
PDDocument newDocument;
PDDocument oldDocument;
try {
newDocument = createNewDocument();
oldDocument = createOldDocument(inputFile);
List<PDPage> oldPages = getAllPages(oldDocument);
oldPages.stream()
.limit(oldPages.size() - OFFSET)
.forEach(page -> {
newDocument.addPage(page);
newDocument.addPage(new PDPage(page.getMediaBox()));
});
newDocument.save(outputFile);
} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
} finally {
newDocument.close();
oldDocument.close();
}
}
Run Code Online (Sandbox Code Playgroud)
对于上面的代码,编译器抱怨在finally块中调用了close()。错误是:“变量 newDocument 可能尚未初始化”。旧文档也一样。
当然,我继续初始化变量,如下所示:
PDDocument newDocument = null;
PDDocument oldDocument = null;
Run Code Online (Sandbox Code Playgroud)
现在我收到编译器错误“lambda 表达式中使用的变量应该是有效的最终变量”。
这件事该怎么办呢?
createNewDocument 和 …
当我看到这个(第 790-811 行)时,我正在阅读源代码:ConcurrentQueue
//We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
//without interuption. This is to prevent anything from happening between them, and another dequeue
//thread maybe spinning forever to wait for m_state[] to be true;
try
{ }
finally
{
newhigh = Interlocked.Increment(ref m_high);
if (newhigh <= SEGMENT_SIZE - 1)
{
m_array[newhigh] = value;
m_state[newhigh].m_value = true;
}
//if this thread takes up the last slot in the segment, …Run Code Online (Sandbox Code Playgroud) 一个简单的控制台应用程序,在 Visual Studio 2019、.Net Framework 4.7、Windows 中:
static void Main(string[] args)
{
try
{
Console.WriteLine("In try");
throw new IndexOutOfRangeException();
}
finally
{ *// Surprisingly this part is not being executed.*
Console.WriteLine("In finally");
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
我确信在没有异常的情况下以及在有异常的情况下都会调用finally块。我在文档中读到:
但是,如果异常未处理,则finally块的执行取决于异常展开操作的触发方式。反过来,这取决于您的计算机的设置方式。
嗯,我很困惑。我是否需要对这个“展开操作”做一些事情,以便在出现未处理的异常时调用finally?
c# finally try-catch console-application unhandled-exception
如果我使用try/catch/finally块我应该在哪里以及如何初始化变量?例如,假设我正在尝试使用FileStream.我想捕获创建或使用流时抛出的任何异常.然后,无论是否有任何问题,我都希望确保创建的任何流都已关闭.
所以我会做这样的事情:
System.IO.FileStream fs;
try
{
fs = new System.IO.FileStream("C:\test.txt", System.IO.FileMode.Open);
//do something with the file stream
}
catch (Exception exp)
{
//handle exceptions
}
finally
{
//ERROR: "unassigned local variable fs"
if (fs != null)
{
fs.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这给了我在finally块中说错误unassigned local variable fs.然而,如果我改变的声明fs,以System.IO.FileStream fs = null它的工作原理.
为什么我需要显式设置fs为null?我也试过fs在try块中声明,但后来我The name fs does not exsist in the current context在finally块中得到了错误.
BTW:我知道我可以使用Using块,但我的问题是要了解try/catch/finally块的正确用法.
受到其他主题的启发,我编写了这个模拟finally块的代码:
#include <cassert>
#include <iostream>
struct base { virtual ~base(){} };
template<typename TLambda>
struct exec : base
{
TLambda lambda;
exec(TLambda l) : lambda(l){}
~exec() { lambda(); }
};
class lambda{
base *pbase;
public:
template<typename TLambda>
lambda(TLambda l): pbase(new exec<TLambda>(l)){}
~lambda() { delete pbase; }
};
class A{
int a;
public:
void start(){
int a=1;
lambda finally = [&]{a=2; std::cout<<"finally executed";};
try{
assert(a==1);
//do stuff
}
catch(int){
//do stuff
}
}
};
int main() {
A …Run Code Online (Sandbox Code Playgroud) public class Foo {
public static void main(String[] args) {
foo();
}
public static void foo() {
try {
System.out.println("try");
foo();
} catch (Throwable e) {
System.out.println("catch");
foo();
} finally {
System.out.println("finally");
foo();
}
}
}
Run Code Online (Sandbox Code Playgroud)
谁能解释一下这段代码的输出?
1.在eclipse(无尽)客户端模式下输出:
try
try
....
...
...
tryfinallyfinally
tryfinallyfinally
try
try
try
tryfinallyfinally
tryfinallyfinally
try
tryfinallyfinally
tryfinallyfinally
try
....
....
2.output on linux(crash)服务器模式:
try
try
...
...
try
try
try
try
try
try
MISSING EXCEPTION HANDLER for pc 0x00002aaaab1c53f0 and handler bci -1
Exception: … 好吧,我已经阅读(并了解到)finally块并不总是执行其代码(甚至除了拔插头之外).
仅供参考.有关更多信息,请参阅try catch finally问题
但是,我没有找到:
当我停止调试器时,我的finally块是否会被执行?
谢谢!
举个这样的例子:
public List<CloseableThing> readThings(List<File> files) throws IOException {
ImmutableList.Builder<CloseableThing> things = ImmutableList.builder();
try {
for (File file : files) {
things.add(readThing(file))
}
return things.build();
} catch (Throwable t) {
for (CloseableThing thing : things.build()) {
thing.close();
}
throw t;
}
}
Run Code Online (Sandbox Code Playgroud)
代码审查评论的出现是因为通常有一条规则不会捕获Throwable.进行此类仅故障清理的旧模式是:
public List<CloseableThing> readThings(List<File> files) throws IOException {
ImmutableList.Builder<CloseableThing> things = ImmutableList.builder();
boolean success = false;
try {
for (File file : files) {
things.add(readThing(file))
}
success = true;
return things.build();
} finally {
if (!success) {
for (CloseableThing …Run Code Online (Sandbox Code Playgroud) 说(可能在一个单独的线程上)我正在运行一些方法ClassA.foobar().在这个方法里面是一个尝试,(可能是捕获),最后阻止.
现在,如果执行仍在try-block(或catch-block)中间时,对此ClassA对象(或此线程)的最后一次引用会丢失,那么此对象(/ thread)是否可以在我获取之前进行垃圾回收到了最后一块?换句话说:即使没有对内存中剩余的对象(/ thread)的强引用,finally块仍然可以保证运行吗?
(我不知道GC如何处理孤立的活线程.)
虚拟的例子:
[Some context]
{
ClassA classA = new ClassA();
//Point is this instance and a reference to it exists
class ClassA
{
public void foobar()
{
try
{
classA = null;
//Point is that the last reference to this instance is lost,
//and that this happens at this point in foobar() execution.
//The actual location of this line of code is irrelevant.
}
finally
{
//some important stuff here!
}
}
}
}
Run Code Online (Sandbox Code Playgroud) java garbage-collection finally thread-safety try-catch-finally
我们在这个论坛上看到过很多关于try-catch-finally和try-finally建设的问题.
答案的数量增加了问题的数量,所以我也很少.
这是Microsoft解释try-finally构建的链接.我已经读过了!
在下面的文章中写道:
在处理的异常中,保证运行关联的finally块.但是,如果未处理异常,则finally块的执行取决于如何触发异常展开操作.反过来,这取决于您的计算机的设置方式.
我是否正确地理解在try-catch-finally施工finally中将永远执行?(不包括Environment.FastFail())
我已经在这个论坛上读到过StackOverFlowException(这个finally块没有在这个场合执行过),但是当我throw这个时,finally块被执行了.那有什么关系StackOverFlowException?
为什么finally不调用块?(在下面的代码中)?
我们一般使用哪些情况try-finally?
从什么PC设置finally块依赖?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
throw new Exception();
}
finally
{
Console.WriteLine("finally");
Console.ReadKey();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)