Soy un programador travieso, y hasta ahora no he manejado los errores correctamente (por ejemplo, simplemente capturando una excepción java.lang.Express, imprimiendo un mensaje de depuración, y moviéndome). Cuando los "manejo", simplemente ha sido cerrar el compilador.Manejo de errores: ¿es este un patrón decente?
Recientemente me enteré del error (jaja) de mis costumbres, y me gustaría empezar a hacerlo bien. Así que lo estoy investigando aquí y en otros lugares (a través de búsquedas en Google).
Supongamos que tengo un bloque de código que hace lo siguiente:
...
x.method1(); // throws ExceptionTypeA
...
y.method2(); // throws ExceptionTypeB
...
z.method3(); // throws ExceptionTypeC
...
x.method4(); // throws ExceptionTypeA (again)
...
De lo que he reunido, la forma correcta de manejar esto es:
try {
...
x.method1(); // throws ExceptionTypeA
...
y.method2(); // throws ExceptionTypeB
...
z.method3(); // throws ExceptionTypeC
...
x.method4(); // throws ExceptionTypeA (again)
...
} catch (ExceptionTypeA e) {
// do something about condition A
} catch (ExceptionTypeB e) {
// do something about condition B
} catch (ExceptionTypeC e) {
// do something about condition C
}
Esto parece bastante sencillo de yo, pero parece desordenado cuando tengo un bloque largo de código que arroja varios errores a lo largo. ¡Parece que terminé con solo un intento/captura gigante en todo mi método! La alternativa parece ser:
try {
...
x.method1(); // throws ExceptionTypeA
...
} catch (ExceptionTypeA e) {
// do something about condition A
}
try {
...
y.method2(); // throws ExceptionTypeB
...
} catch (ExceptionTypeB e) {
// do something about condition A
}
try {
...
z.method3(); // throws ExceptionTypeC
...
} catch (ExceptionTypeC e) {
// do something about condition C
}
try {
...
x.method4(); // throws ExceptionTypeA
...
} catch (ExceptionTypeA e) {
// do something about condition A
}
Esto se ve realmente desagradable. En casos como este, he considerado hacer algo como lo siguiente:
private void doSomething() throws exceptionTypeA, exceptionTypeB, exceptionTypeC {
...
x.method1(); // throws ExceptionTypeA
...
y.method2(); // throws ExceptionTypeB
...
z.method3(); // throws ExceptionTypeC
...
x.method4(); // throws ExceptionTypeA (again)
...
}
public void doSomething_andHandleErrors() {
try {
this.toSomething();
} catch (ExceptionTypeA e) {
// do something about condition A
} catch (ExceptionTypeB e) {
// do something about condition B
} catch (ExceptionTypeC e) {
// do something about condition C
}
}
... y luego doSomething_andHandleErrors sólo llamar(); desde afuera. ¿Es esta una buena practica? ¿Estoy cayendo en algún antipatrón?
Gracias!
Me movería esto a http://codereview.stackexchange.com –