この Java コードでは、
import java.io.IOException;
public class Copy
{
public static void main(String[] args)
{
if (args.length != 2)
{
System.err.println("usage: java Copy srcFile dstFile");
return;
}
int fileHandleSrc = 0;
int fileHandleDst = 1;
try
{
fileHandleSrc = open(args[0]);
fileHandleDst = create(args[1]);
copy(fileHandleSrc, fileHandleDst);
}
catch (IOException ioe)
{
System.err.println("I/O error: " + ioe.getMessage());
return;
}
finally
{
close(fileHandleSrc);
close(fileHandleDst);
}
}
static int open(String filename)
{
return 1; // Assume that filename is mapped to integer.
}
static int create(String filename)
{
return 2; // Assume that filename is mapped to integer.
}
static void close(int fileHandle)
{
System.out.println("closing file: " + fileHandle);
}
static void copy(int fileHandleSrc, int fileHandleDst) throws IOException
{
System.out.println("copying file " + fileHandleSrc + " to file " +
fileHandleDst);
if (Math.random() < 0.5)
throw new IOException("unable to copy file");
System.out.println("After exception");
}
}
私が期待する出力は
copying file 1 to file 2
I/O error: unable to copy file
closing file: 1
closing file: 2
ただし、この予想される出力が得られることもあれば、次の出力が得られることもあります。
copying file 1 to file 2
closing file: 1
closing file: 2
I/O error: unable to copy file
そして時々この出力さえ:
I/O error: unable to copy file
copying file 1 to file 2
closing file: 1
closing file: 2
そして、最初、2番目、または3番目の出力を取得するかどうかは、実行ごとにランダムに発生するようです。明らかに同じ問題について話しているTHIS POSTを見つけましたが、出力 1、2、または 3 を取得する理由がまだわかりません。このコードを正しく理解していれば、出力 1 が毎回取得されるはずです (例外が発生します)。 )。出力 1 を一貫して取得する方法、または出力 1 を取得する時期または出力 2 または 3 を取得する時期を判断できるようにするにはどうすればよいですか?