在查看我的代码覆盖率时,我注意到很多单元测试无法检查最终块,这些块试图关闭finally块中的打开InputStreams.
一个示例摘录是:
try {
f = new BufferedInputStream(new FileInputStream(source));
f.read(buffer);
} finally {
if (f != null)
try {
f.close();
} catch (IOException ignored) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有适当的解决方案来使用JUnit4检查finally块内的所有内容?
我知道在保持最高生产力的同时,无法实现100%的代码覆盖率.然而,这些红线在报告中引人注目.
我有一个具有良好定义的Try/Catch/Finally链的应用程序,它在正常条件下退出并执行finally块,但是当有人过早地点击GUI中的红色X时,程序完全存在(代码= 0)并且主线程的finally块未被调用.
事实上,我确实希望程序在点击red-X时退出,但我不想要的是跳过finally {}块!我在GUI中手动放入finally块的最重要部分,但我真的不希望这样做,因为我希望GUI与实际程序分离:
class GUI { // ...
...
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
try {
processObject.getIndicatorFileStream().close();
} catch (Exception ignore) {}
System.exit(0);
}
});
...
}
Run Code Online (Sandbox Code Playgroud)
但我更喜欢这样的电话:
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Run Code Online (Sandbox Code Playgroud)
并确保在Exit之后从每个线程调用所有finally {}块.
我知道这实际上是预期的.如果应用程序从一个单独的线程(比如GUI线程)关闭,那么主线程将停在其轨道上.
简而言之 - 我如何确保System.exit(0)或JFrame.EXIT_ON_CLOSE仍然会导致每个线程的finally块执行?
你如何格式化try..catch.finally块?特别是当它只包含少量代码时,它会使所有内容都受到影响,并且在我看来代码变得难以理解和难看.
如:
try
{
MyService service = new Service();
service.DoSomething();
return something;
}
catch (Exception ex)
{
LogSomething();
return somethingElse;
}
finally
{
MarkAsComplete();
service.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
这7行代码变成了16行混乱.
有关更好的try..catch ..最终格式化的任何建议?
我尝试捕获finally块,如果发生一些异常,我将从catch块返回,所以最后块仍然执行,如果是的话,什么时候?返回之前还是返回之后?
这是正确的做法吗?
try
{
// do something
}
catch (Exception)
{
return false;
}
finally
{
if (connection.State == ConnectionState.Open) connection.Close();
}
Run Code Online (Sandbox Code Playgroud) 我有以下Java类做一件事,从config.properties中激活值.
当关闭时fileInputStream,我想我在维基百科上读到,最好将它放在最后一个块中.因为它诚实地在try/catch块中工作得很好.
你能告诉我修正fileInputStream.close()最后一节吗?
ConfigProperties.java包基;
import java.io.FileInputStream;
import java.util.Properties;
public class ConfigProperties {
public FileInputStream fileInputStream;
public String property;
public String getConfigProperties(String strProperty) {
Properties configProperties = new Properties();
try {
fileInputStream = new FileInputStream("resources/config.properties");
configProperties.load(fileInputStream);
property = configProperties.getProperty(strProperty);
System.out.println("getConfigProperties(" + strProperty + ")");
// use a finally block to close your Stream.
// If an exception occurs, do you want the application to shut down?
} catch (Exception ex) {
// TODO
System.out.println("Exception: " + ex); …Run Code Online (Sandbox Code Playgroud) 我正在努力 My application's under maintanace module
try {
if (isUndermaintanace) {
System.exit(1);
} else {
prepareResources();
}
} catch (Exception e) {
printStack(e);
} finally {
cleanResources();
}
Run Code Online (Sandbox Code Playgroud)
当我通过 isundermaintanace true 最后没有执行.
我错过了什么?还有其他办法吗?
当一个异常可能在 finally 块中抛出时如何传播这两个异常 - 从 catch 和 from finally?
作为一种可能的解决方案 - 使用 AggregateException:
internal class MyClass
{
public void Do()
{
Exception exception = null;
try
{
//example of an error occured in main logic
throw new InvalidOperationException();
}
catch (Exception e)
{
exception = e;
throw;
}
finally
{
try
{
//example of an error occured in finally
throw new AccessViolationException();
}
catch (Exception e)
{
if (exception != null)
throw new AggregateException(exception, e);
throw;
}
}
}
} …Run Code Online (Sandbox Code Playgroud) 这样的代码有什么区别:
string path = @"c:\users\public\test.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
还有这个:
string path = @"c:\users\public\test.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
} …Run Code Online (Sandbox Code Playgroud) 我有这个方法,我正在尝试使用Java SE 7的资源.
private void generateSecretWord(String filename){
try (FileReader files = new FileReader(filename)){
Scanner input = new Scanner(files);
String line = input.nextLine();
String[] words = line.split(",");
Collections.shuffle(Arrays.asList(words));
if (words[0].length()>1){
secretWord = words[0];
return;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (files!=null) files.close();
}
}
Run Code Online (Sandbox Code Playgroud)
我在finally块中得到编译错误,files cannot be resolved to a variable
我在文件中引用了文件try with block.为什么我会收到此错误以及如何解决?
谢谢
假设我要编写一个捕获KeyboardInterrupt异常的Python脚本,以便用户能够安全地使用Ctrl+ 终止C
但是,我无法将所有关键操作(如文件写入)放入catch块中,因为它依赖于局部变量并确保后续Ctrl+ C无论如何都不会破坏它.
使用带有empty(pass)try部分的try-catch块以及部件中的所有代码finally将这个片段定义为"原子,中断安全代码"并且可能不会在中途中断时,它是否有效并且是一种好习惯?
例:
try:
with open("file.txt", "w") as f:
for i in range(1000000):
# imagine something useful that takes very long instead
data = str(data ** (data ** data))
try:
pass
finally:
# ensure that this code is not interrupted to prevent file corruption:
f.write(data)
except KeyboardInterrupt:
print("User aborted, data created so far saved in file.txt")
exit(0)
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我不关心当前生成的数据字符串,即可以中断创建并且不会触发写入.但是一旦写入开始,就必须完成,这就是我想要确保的.此外,如果在finally子句中执行写入时发生异常(或KeyboardInterrupt)会发生什么?
python try-catch try-catch-finally keyboardinterrupt try-finally
java ×5
c# ×4
try-catch ×2
exit ×1
finally ×1
formatting ×1
java-6 ×1
jframe ×1
junit4 ×1
oop ×1
python ×1
return-value ×1
system.exit ×1
try-finally ×1