Diferencia entre try-finally y try-catch


¿Cuál es la diferencia entre

try {
    fooBar();
} finally {
    barFoo();
}

Y

try {
  fooBar();
} catch(Throwable throwable) {
    barFoo(throwable); // Does something with throwable, logs it, or handles it.
}

Me gusta más la segunda versión porque me da acceso al Lanzable. ¿Hay alguna diferencia lógica o una convención preferida entre las dos variaciones?

Además, ¿hay alguna forma de acceder a la excepción de la cláusula finally?

Author: Vijay Kotari, 2010-05-18

10 answers

Estas son dos cosas diferentes:

  • El bloque catch solo se ejecuta si se lanza una excepción en el bloque try.
  • El bloque finally se ejecuta siempre después del bloque try(-catch), si se lanza una excepción o no.

En tu ejemplo no has mostrado la tercera construcción posible:

try {
    // try to execute this statements...
}
catch( SpecificException e ) {
    // if a specific exception was thrown, handle it here
}
// ... more catches for specific exceptions can come here
catch( Exception e ) {
    // if a more general exception was thrown, handle it here
}
finally {
    // here you can clean things up afterwards
}

Y, como dice @codeca en su comentario, no hay forma de acceder a la excepción dentro del bloque finally, porque el bloque finally se ejecuta incluso si hay no es una excepción.

Por supuesto, puede declarar una variable que contenga la excepción fuera de su bloque y asignar un valor dentro del bloque catch. Después puedes acceder a esta variable dentro de tu bloque finally.

Throwable throwable = null;
try {
    // do some stuff
}
catch( Throwable e ) {
    throwable = e;
}
finally {
    if( throwable != null ) {
        // handle it
    }
}
 102
Author: tangens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-22 22:27:02

Estas no son variaciones, son cosas fundamentalmente diferentes. {[0] } se ejecuta siempre, catch solo cuando ocurre una excepción.

 11
Author: Michiel Buddingh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-18 06:17:49

Finalmente y los bloques de captura son bastante diferentes:

  • Dentro del bloque catch puedes responder a la excepción lanzada. Este bloque se ejecuta solo si hay una excepción no controlada y el tipo coincide con la subclase one or is de la especificada en el parámetro catch block.
  • Finalmente se ejecutará siempre después de intentar y atrapar bloques si hay una excepción planteada o no.

So

try {
  //some code
}
catch (ExceptionA) {
  // Only gets executed if ExceptionA 
  // was thrown in try block
}
catch (ExceptionB) {
  // Only executed if ExceptionB was thrown in try 
  // and not handled by first catch block
}

Difiere de

try {
  //some code
}
finally {
  // Gets executed whether or not 
  // an exception was thrown in try block
}

Significativamente.

Si defines un bloque try tienes que definir

  1. un bloque final, o
  2. uno o más bloques de captura, o
  3. uno o más bloques de captura y uno finalmente bloque

Así que el siguiente código también sería válido:

try {
  //some code
}
catch (ExceptionA) {
  // Only gets executed if 
  // ExceptionA was thrown in try block
}
catch (ExceptionB) {
  // Only executed if ExceptionB was thrown in 
  // try and not handled by first catch block
}
//even more catch blocks
finally {
  // Gets executed whether or not an 
  // exception was thrown in try block
}
 6
Author: TheMorph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-13 15:57:50
try {
    statements;
} catch (exceptionType1 e1) {      // one or multiple
    statements;                 
} catch (exceptionType2 e2) {
    statements;
}    
...
} finally {                                 // one or none
    statements;
}
  1. Todas las declaraciones try deben incluir una cláusula catch o una cláusula finally
  2. Puede tener varias cláusulas de captura, pero solo una cláusula final
  3. Durante cualquier ejecución, si ocurre algún error, entonces el Control se transfiere al bloque Catch apropiado y ejecuta las instrucciones y Finalmente se ejecuta block.

No importa lo que El bloque Finally siempre se ejecuta, Por lo que en General, Se utiliza el bloque Finally, cuando tiene sesiones, Base de datos las conexiones o Archivos o sockets están abiertos, luego se colocará el código para cerrar esas conexiones. Esto es solo para asegurarse de que en una aplicación no se produzcan fugas de memoria ni ningún otro problema.

 4
Author: gmhk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-18 07:15:52

Finalmente los bloques catch son bastante diferentes:

Dentro del bloque catch puede responder a la excepción lanzada. Este bloque se ejecuta solo si hay una excepción no controlada y el tipo coincide con la subclase one or is de la especificada en el parámetro catch block. Finalmente se ejecutará siempre después de intentar y coger bloques si hay una excepción planteada o no.

 4
Author: Mohammad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-11 16:01:57

Try se utiliza para ejecutar un método que puede lanzar una excepción

Catch se usa para" catch " detener esa excepción

Finalmente se utiliza para cualquier limpieza necesaria de que la excepción se captura o no

try{
    myObject.riskyMethod(); // run a method that may throw an exception
}
catch(Exception ex){
    myLogger.log(ex.Message); // "catch" stop that exception
}
finally{
    myObject = null; // clean up needed from that exception being caught
}
 4
Author: Kieran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-15 00:12:07

En Mi investigación, Finalmente, el bloque siempre se ejecuta y se usa principalmente para "cerrar las conexiones abiertas" y para destruir algo que se está ejecutando innecesariamente.

 3
Author: Hari krishna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-14 08:26:24

Finalmente el bloque siempre se ejecuta. Catch block solo se ejecuta cuando se captura una excepción que coincide con el parámetro blocks.

 2
Author: mkorpela,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-18 06:18:11

Incluso en el primer formulario se puede registrar en el método de llamada. Así que no hay gran ventaja a menos que quiera hacer un manejo especial allí.

 2
Author: fastcodejava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-27 02:36:53

Generalmente cuando usamos cualquier recurso como flujos, conexiones, etc.. tenemos que cerrarlos explícitamente usando finally block. En el programa que se muestra a continuación, estamos leyendo datos de un archivo utilizando FileReader y lo estamos cerrando utilizando finally block.

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadData_Demo {

   public static void main(String args[]){
      FileReader fr=null;       
      try{
         File file=new File("file.txt");
         fr = new FileReader(file);  char [] a = new char[50];
         fr.read(a); // reads the content to the array
         for(char c : a)
         System.out.print(c); //prints the characters one by one
      }catch(IOException e){
          e.printStackTrace();
       }
       finally{ 
          try{
              fr.close();
          }catch(IOException ex){       
               ex.printStackTrace();
           }
       }
    }

}

Tal vez otros tipos como yo buscaron algo como esto.

Información de esta página tutpoint

 2
Author: Florian Neiss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-12 08:32:38