In diesem Java-Code,Was ist die genaue Reihenfolge der Ausführung für versuchen, fangen und schließlich?
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");
}
}
die Ausgabe, die ich erwarte, ist
copying file 1 to file 2
I/O error: unable to copy file
closing file: 1
closing file: 2
aber manchmal bekomme ich diese erwartete Ausgabe und zu anderen Zeiten erhalte ich folgende Ausgabe:
copying file 1 to file 2
closing file: 1
closing file: 2
I/O error: unable to copy file
und manchmal sogar diese Ausgabe:
I/O error: unable to copy file
copying file 1 to file 2
closing file: 1
closing file: 2
und ob ich die erste, zweite oder dritte Ausgabe bekomme scheint zufällig bei jeder Ausführung passieren. Ich fand THIS POST, die anscheinend über das gleiche Problem spricht, aber ich verstehe immer noch nicht, warum ich manchmal 1, 2 oder 3 bekomme. Wenn ich diesen Code richtig verstehe, dann sollte Ausgabe 1 sein, was ich jedes Mal bekomme (die Ausnahme tritt auf) . Wie stelle ich sicher, dass ich Output 1 konsistent erhalte oder in der Lage bin zu sagen, wann ich Output 1 bekomme oder wann ich Output 2 oder 3 bekomme?
möglich Duplikat [Random Druckauftrag für System.out & System.err ruft] (http://stackoverflow.com/questions/12594537/ random-printing-order-für-system-out-system-err-calls) – user93353