Domanda

C'è un modo di rilevare, la clausola finally, che un'eccezione è in procinto di essere lanciata?

Vedi l'esempio qui sotto:


try {
    // code that may or may not throw an exception
} finally {
    SomeCleanupFunctionThatThrows();
    // if currently executing an exception, exit the program,
    // otherwise just let the exception thrown by the function
    // above propagate
}

o sta ignorando una delle eccezioni l'unica cosa che si può fare?

In C++ non ti consente di ignorare una delle eccezioni e solo chiamate terminate().La maggior parte delle altre lingue usano le stesse regole come java.

È stato utile?

Soluzione

Impostare una variabile di flag, quindi controllare per essa la clausola finally, in questo modo:

boolean exceptionThrown = true;
try {
   mightThrowAnException();
   exceptionThrown = false;
} finally {
   if (exceptionThrown) {
      // Whatever you want to do
   }
}

Altri suggerimenti

Se ti trovi a fare questo, allora si potrebbe avere un problema con il vostro disegno.L'idea di un "finalmente" blocco è che si desidera qualcosa di fatto a prescindere di come il metodo di uscite.Mi sembra come se non c'è bisogno di un blocco finally a tutti, e dovrebbe utilizzare i blocchi try-catch:

try {
   doSomethingDangerous(); // can throw exception
   onSuccess();
} catch (Exception ex) {
   onFailure();
}

Se una funzione genera e si desidera catturare l'eccezione, dovrete avvolgere la funzione in un blocco try, è il modo più sicuro.Quindi nel tuo esempio:

try {
    // ...
} finally {
    try {
        SomeCleanupFunctionThatThrows();
    } catch(Throwable t) { //or catch whatever you want here
        // exception handling code, or just ignore it
    }
}

Vuoi dire che si desidera che il blocco finally agiscono in modo diverso a seconda che il blocco try completato con successo?

Se è così, si può sempre fare qualcosa di simile:

boolean exceptionThrown = false;
try {
    // ...
} catch(Throwable t) {
    exceptionThrown = true;
    // ...
} finally {
    try {
        SomeCleanupFunctionThatThrows();
    } catch(Throwable t) { 
        if(exceptionThrown) ...
    }
}

Che sta facendo abbastanza contorto, però...si potrebbe desiderare di pensare a un modo per ristrutturare il tuo codice per fare questo inutile.

No non credo.Il blocco catch verrà eseguito a compimento prima del blocco finally.

try {
    // code that may or may not throw an exception
} catch {
// catch block must exist.
finally {
    SomeCleanupFunctionThatThrows();
// this portion is ran after catch block finishes
}

Altrimenti si può aggiungere un sincronizzare() oggetto il codice di eccezione da usare, che si può verificare nel blocco finally, che potrebbe aiutare a identificare se è in una stanza separata thread in esecuzione di un'eccezione.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top