In questo codice java,qual è l'esatto ordine di esecuzione per provare, prendere e, infine?
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");
}
}
l'output che mi aspetto è
copying file 1 to file 2
I/O error: unable to copy file
closing file: 1
closing file: 2
Tuttavia a volte ottengo questo output previsto e altre volte ottengo il seguente output:
copying file 1 to file 2
closing file: 1
closing file: 2
I/O error: unable to copy file
ea volte anche questa uscita:
I/O error: unable to copy file
copying file 1 to file 2
closing file: 1
closing file: 2
e se ottengo la prima, seconda o terza uscita sembra accadere casualmente durante ogni esecuzione. Ho trovato THIS POST che sembra parlare dello stesso problema, ma ancora non capisco perché a volte ottengo l'output 1, 2 o 3. Se capisco correttamente questo codice, l'output 1 dovrebbe essere quello che ottengo ogni volta (si verifica l'eccezione) . Come faccio a essere sicuro di ottenere l'output 1 in modo coerente, o di essere in grado di dire quando riceverò l'output 1 o quando riceverò l'output 2 o 3 per ?
possibile duplicato del [ordine di stampa a caso per System.out & System.err chiamate] (http://stackoverflow.com/questions/12594537/ random-printing-order-for-system-out-system-err-calls) – user93353