W tym kodzie java,jaka jest dokładna kolejność wykonania dla try, catch i wreszcie?
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");
}
}
wyjście że spodziewam się
copying file 1 to file 2
I/O error: unable to copy file
closing file: 1
closing file: 2
Jednak czasami otrzymuję ten oczekiwany wynik, a czasami pojawia się następujący komunikat:
copying file 1 to file 2
closing file: 1
closing file: 2
I/O error: unable to copy file
, a czasami nawet to wyjście:
I/O error: unable to copy file
copying file 1 to file 2
closing file: 1
closing file: 2
i czy pierwsze, drugie lub trzecie wyjście wydaje się przypadkowe podczas każdej realizacji. Znalazłem THIS POST, który najwyraźniej mówi o tym samym problemie, ale nadal nie rozumiem, dlaczego czasami otrzymuję wyjście 1, 2 lub 3. Jeśli rozumiem ten kod poprawnie, to wynik 1 powinien być tym, co dostaję za każdym razem (pojawia się wyjątek) . W jaki sposób zapewnić, że otrzymuję wynik 1 w sposób ciągły lub będę w stanie określić, kiedy otrzymam dane wyjściowe 1 lub kiedy będę uzyskiwał wynik 2 lub 3?
możliwy duplikat [losowej kolejności drukowania dla System.out & System.err nazywa] (http://stackoverflow.com/questions/12594537/ random-printing-order-for-system-out-system-err-calls) – user93353