They are avoided, not handled. The compiler says nothing.
Checked · Exception
Environment conditions
Expected and out of your control. The compiler forces you to decide.
throw
An action
throw new EdadInvalidaException(edad);
throws
A warning
void setEdad(int e) throws EdadInvalidaException
Not where it happens
Reading a file rarely knows what to do if it is missing.
Where you can decide
The one who asked for the read knows whether to retry, warn or use a default.
A catch that is not needed
If it cannot make any useful decision, do not write it.
Order
From specific to general
If you swap the order, the compiler stops you.
multi-catch
catch (IOException | SQLException e)
A single block when two types are handled the same way.
By hand
Nine lines of ceremony
null check, a close() that can also fail and almost nobody knows what to put.
AutoCloseable
A simulated resource
It prints one message when it opens and another when it closes.
try-with-resources
The closing no longer depends on you
It works with any AutoCloseable class.
Domain exception
SaldoInsuficienteException
It tells you what happened from its name.
Carries data
e.getFaltante()
Not just a text: the catch can use them.
extends Exception · checked
Expected environment condition: configuration file not found.
extends RuntimeException · unchecked
API usage error: the caller should have validated first. The most common today.
1 The empty catch
A swallowed error is infinitely worse than a visible one.
2 Catching Exception up front
It also catches the bugs that were meant to blow up early.
3 Normal flow control
A user not existing is not exceptional, it is just Tuesday.
4 return inside finally
It silently discards the traveling exception.
Empty catchcatch (Exception e) firstGeneral catch before the specific oneRethrowing without the causeFifty-line tryClosing resources by handExceptions for normal cases
1 Step
EdadInvalidaException
extends RuntimeException + rejected age
2 Step
registrar(nombre, edad)
The range rule, in a single place
3 Step
registrarDesdeTexto(…)
Translates NumberFormatException, keeps the cause
4 Step
main
Valid case, out of range and invalid text
5 Step
finally
A record that the attempt finished
1 · An exception is an object2 · Unchecked is avoided, checked forces you3 · The try is cut; the finally always runs4 · Travels up the stack to a catch5 · From specific to general6 · try-with-resources to close7 · When rethrowing, pass the cause8 · An empty catch is worse than nothing
In the constructors lesson, setPrecio returned false when it rejected a negative price.
But nothing forces the caller to look at that result.
The price stays as it was, with no warning, and the program carries on as if nothing happened.
A crack in setPrecio
In the constructors lesson, setPrecio returned false when it rejected a negative price. But nothing forces the caller to look at that result. The price stays as it was, with no warning, and the program carries on as if nothing happened.
With an exception, setPrecio throws an object that describes the problem.
Normal execution is interrupted until somebody catches it.
If nobody catches it, the program stops: there is no way to pretend nothing happened.
A way of failing that cannot be ignored
With an exception, setPrecio throws an object that describes the problem. Normal execution is interrupted until somebody catches it. If nobody catches it, the program stops: there is no way to pretend nothing happened.
The file is missing, the network drops, the user types "twenty-two" where a number belongs.
The question is not whether it will fail, but what your code does when it does.
A real program fails all the time
The file is missing, the network drops, the user types "twenty-two" where a number belongs. The question is not whether it will fail, but what your code does when it does.
Everything that can be thrown hangs from Throwable, the root of the hierarchy.
Below it are two branches: Error, for JVM failures, and Exception.
And RuntimeException hangs from Exception, with its children.
The Throwable hierarchy
Everything that can be thrown hangs from Throwable, the root of the hierarchy. Below it are two branches: Error, for JVM failures, and Exception. And RuntimeException hangs from Exception, with its children.
Exception outside RuntimeException is CHECKED: the compiler forces you to deal with it.
Everything under RuntimeException is UNCHECKED: the compiler says nothing.
Who forces you: checked and unchecked
Exception outside RuntimeException is CHECKED: the compiler forces you to deal with it. Everything under RuntimeException is UNCHECKED: the compiler says nothing.
An Error, like OutOfMemoryError, is not caught: there is nothing you can do.
If the JVM ran out of memory, your catch will not be able to run either.
Error: do not catch it
An Error, like OutOfMemoryError, is not caught: there is nothing you can do. If the JVM ran out of memory, your catch will not be able to run either.
An exception is not an error code: it is an instance of a class.
getMessage() returns the description and getCause() the original exception, if any.
getStackTrace() keeps the path and printStackTrace() prints it to the error output.
An exception carries information
An exception is not an error code: it is an instance of a class. getMessage() returns the description and getCause() the original exception, if any. getStackTrace() keeps the path and printStackTrace() prints it to the error output.
The try holds the code that may fail.
The catch catches the exception, if the type matches.
The finally runs no matter what, and then the program continues.
The three blocks
The try holds the code that may fail. The catch catches the exception, if the type matches. The finally runs no matter what, and then the program continues.
Without an exception, the try runs completely, up to its last line.
The catch is skipped entirely: there was nothing to catch.
The finally runs anyway and the program continues normally.
Without an exception
Without an exception, the try runs completely, up to its last line. The catch is skipped entirely: there was nothing to catch. The finally runs anyway and the program continues normally.
Now the divisor is zero: the try is CUT at that line.
The following lines never run: B does not show up in the output.
The exception travels to the catch; then the finally runs and the code goes on.
With an exception
Now the divisor is zero: the try is CUT at that line. The following lines never run: B does not show up in the output. The exception travels to the catch; then the finally runs and the code goes on.
Even with a return inside the try, the finally runs before leaving.
What does not run is the code that was left after it: the method is already over.
The finally always runs
Even with a return inside the try, the finally runs before leaving. What does not run is the code that was left after it: the method is already over.
Output: A, C, D. Line B never runs.
That is why try blocks should be short: a forty-line try is a mystery.
The try is cut: A, C, D
Output: A, C, D. Line B never runs. That is why try blocks should be short: a forty-line try is a mystery.
Flujo.javajava
publicclassFlujo{publicstaticvoidmain(String[] args){try{System.out.println("A");int x =10/0;// ← thrown hereSystem.out.println("B");// ← NEVER runs}catch(ArithmeticException e){System.out.println("C");}System.out.println("D");}}
Terminalbash
java FlujoACD
Unchecked exceptions are programming errors: a NullPointerException is avoided, not handled.
The compiler puts up no barrier: they just go through.
The fix is not a catch, it is fixing the code.
Unchecked: programming errors
Unchecked exceptions are programming errors: a NullPointerException is avoided, not handled. The compiler puts up no barrier: they just go through. The fix is not a catch, it is fixing the code.
Checked exceptions are expected conditions of the environment: the file is missing, the service is down.
Here the compiler stops the way and forces you to decide.
Checked: environment conditions
Checked exceptions are expected conditions of the environment: the file is missing, the service is down. Here the compiler stops the way and forces you to decide.
There are only two options. Handle it with try/catch…
…or declare with throws that you do not handle it, and let your caller decide.
Handle it or declare it
There are only two options. Handle it with try/catch… …or declare with throws that you do not handle it, and let your caller decide.
NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException: all unchecked.
The bug is the null, the index 5 or the unvalidated input, not the exception.
Unchecked: you avoid them
NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException: all unchecked. The bug is the null, the index 5 or the unvalidated input, not the exception.
Bugs.javajava
String s =null;s.length();// NullPointerException — the bug is the nullint[] a =newint[3];a[5]=1;// ArrayIndexOutOfBoundsException — the bug is the 5Integer.parseInt("hola");// NumberFormatException — validate the input first
Scanner.nextInt() throws InputMismatchException: it is unchecked, a child of RuntimeException.
When it fails, the invalid text stays in the buffer: without nextLine() the loop fails again and again.
InputMismatchException and the buffer
Scanner.nextInt() throws InputMismatchException: it is unchecked, a child of RuntimeException. When it fails, the invalid text stays in the buffer: without nextLine() the loop fails again and again.
Edad.javajava
Scanner leer =newScanner(System.in);int edad =0;boolean valido =false;while(!valido){try{edad = leer.nextInt();// InputMismatchException if they type "abc"valido =true;}catch(InputMismatchException e){System.out.println("Enter a number.");leer.nextLine();// discards the invalid text from the buffer}}
Terminalbash
java EdadabcIngresá un número.22(la edad es 22)
obtenerConfiguracion() declares throws ConfiguracionNoDisponibleException: it is checked.
Either you handle it with a catch, or you declare it in your signature and let your caller decide.
Checked: two options
obtenerConfiguracion() declares throws ConfiguracionNoDisponibleException: it is checked. Either you handle it with a catch, or you declare it in your signature and let your caller decide.
Configuracion.javajava
// Option 1: handle itpublicvoidleerConfiguracion(){try{String valor =obtenerConfiguracion();System.out.println(valor);}catch(ConfiguracionNoDisponibleException e){System.out.println("Using the default values.");}}// Option 2: declare that you do not handle itpublicStringleerConfiguracion()throwsConfiguracionNoDisponibleException{returnobtenerConfiguracion();// let the caller decide}
throw is an action: it throws the object, inside the method.
throws is a warning: it goes in the signature and tells what may come out.
throw and throws are not the same
throw is an action: it throws the object, inside the method. throws is a warning: it goes in the signature and tells what may come out.
Each call stacks a frame: main calls procesarArchivo, which calls leerLinea…
…which finally calls Integer.parseInt with the text "veintidós".
The call stack
Each call stacks a frame: main calls procesarArchivo, which calls leerLinea… …which finally calls Integer.parseInt with the text "veintidós".
parseInt cannot convert "veintidós" and throws a NumberFormatException.
The exception is born here, in the topmost frame.
The exception is born
parseInt cannot convert "veintidós" and throws a NumberFormatException. The exception is born here, in the topmost frame.
This frame has no catch: it is abandoned and its remaining code does not run.
The exception goes to the method that called it, leerLinea, which does not catch it either.
And on it goes: procesarArchivo does not know what to do with it either.
It travels up the stack
This frame has no catch: it is abandoned and its remaining code does not run. The exception goes to the method that called it, leerLinea, which does not catch it either. And on it goes: procesarArchivo does not know what to do with it either.
In main there is a catch whose type matches: here the exception stops.
The handler runs and the program carries on.
Somebody catches it
In main there is a catch whose type matches: here the exception stops. The handler runs and the program carries on.
That path is recorded in the exception’s stack trace.
Each line is a frame: where it was born and who it went through until the catch.
The stack trace is the path
That path is recorded in the exception’s stack trace. Each line is a frame: where it was born and who it went through until the catch.
If nobody catches it, it reaches the end of the stack and the JVM prints the stack trace.
The thread ends: an uncaught exception cannot be ignored.
If nobody catches it
If nobody catches it, it reaches the end of the stack and the JVM prints the stack trace. The thread ends: an uncaught exception cannot be ignored.
You do not catch where the error happens, but where you can do something about it.
A method that reads a file rarely knows what to do if it is missing; the one that asked for the read does.
A catch that cannot make any useful decision is a catch that is not needed.
Catch where you can do something
You do not catch where the error happens, but where you can do something about it. A method that reads a file rarely knows what to do if it is missing; the one that asked for the read does. A catch that cannot make any useful decision is a catch that is not needed.
Java tries the catch blocks in order and runs the first one whose type matches.
A NumberFormatException lands in the first one: it is the most specific.
The order of the catch blocks
Java tries the catch blocks in order and runs the first one whose type matches. A NumberFormatException lands in the first one: it is the most specific.
An IllegalArgumentException skips the first one and lands in the second.
And any other, like IOException, ends up in the final catch (Exception e).
From specific to general
An IllegalArgumentException skips the first one and lands in the second. And any other, like IOException, ends up in the final catch (Exception e).
If you put Exception first, it catches everything and the catch blocks below could never run.
The compiler stops you: compile error, unreachable catch.
If you swap the order
If you put Exception first, it catches everything and the catch blocks below could never run. The compiler stops you: compile error, unreachable catch.
When two different types are handled the same way, do not duplicate the block.
With multi-catch, IOException | SQLException, a single catch catches both.
Multi-catch
When two different types are handled the same way, do not duplicate the block. With multi-catch, IOException | SQLException, a single catch catches both.
The catch blocks go from the most specific to the most general.
And multi-catch avoids duplicating the block when two types are handled the same way.
Several catch blocks in code
The catch blocks go from the most specific to the most general. And multi-catch avoids duplicating the block when two types are handled the same way.
VariosCatch.javajava
try{procesar(datos);}catch(NumberFormatException e){// most specific firstSystem.out.println("The value is not a valid number.");}catch(IllegalArgumentException e){// NumberFormatException extends thisSystem.out.println("Invalid argument.");}catch(Exception e){// the most general, lastSystem.out.println("Unexpected error.");}try{conectarYGuardar();}catch(IOException|SQLException e){// multi-catchlogger.error("Persistence failed: "+ e.getMessage());}
Opening a file or a connection means you must close it, above all if something fails midway.
Doing it by hand is nine lines of ceremony and two edge cases that almost everyone forgets.
Closing by hand: too much ceremony
Opening a file or a connection means you must close it, above all if something fails midway. Doing it by hand is nine lines of ceremony and two edge cases that almost everyone forgets.
Manual.javajava
ConexionSimulada conexion =null;try{conexion =newConexionSimulada("servidor-datos");conexion.enviar("SELECT * FROM productos");}catch(IllegalArgumentException e){System.out.println("Could not connect.");}finally{if(conexion !=null){// what if building it failed?try{conexion.close();// closing can also throw}catch(Exception e){// and here almost nobody knows what to put}}}
To see the mechanism without files, we simulate a resource that implements AutoCloseable.
It prints one message when it opens and another when it closes, so the exact order shows.
AutoCloseable
To see the mechanism without files, we simulate a resource that implements AutoCloseable. It prints one message when it opens and another when it closes, so the exact order shows.
ConexionSimulada.javajava
publicclassConexionSimuladaimplementsAutoCloseable{privatefinalString servidor;publicConexionSimulada(String servidor){if(servidor ==null|| servidor.isBlank()){thrownewIllegalArgumentException("The server cannot be empty");}this.servidor = servidor;System.out.println("Connecting to "+ servidor +"...");}publicvoidenviar(String comando){System.out.println("Sending: "+ comando);}@Overridepublicvoidclose(){System.out.println("Connection to "+ servidor +" closed.");}}
In try-with-resources the resource is declared inside the parentheses of the try.
It opens on entry and is used inside the block: "Connecting…", "Sending…".
And it closes by itself, even if you do not write it: Java calls close() for you.
It opens, is used and closes by itself
In try-with-resources the resource is declared inside the parentheses of the try. It opens on entry and is used inside the block: "Connecting…", "Sending…". And it closes by itself, even if you do not write it: Java calls close() for you.
A block can end in three ways: normally, with an exception or with a return.
All three paths converge on the same point: close() always runs.
It runs before the catch or the finally. There is no way to forget it.
Three paths, one closing
A block can end in three ways: normally, with an exception or with a return. All three paths converge on the same point: close() always runs. It runs before the catch or the finally. There is no way to forget it.
One single block, no finally or null checks: the closing no longer depends on you.
It works with any AutoCloseable class, and you can declare several resources separated by semicolons.
The same code with try-with-resources
One single block, no finally or null checks: the closing no longer depends on you. It works with any AutoCloseable class, and you can declare several resources separated by semicolons.
ConTryWithResources.javajava
try(ConexionSimulada conexion =newConexionSimulada("servidor-datos")){conexion.enviar("SELECT * FROM productos");}catch(IllegalArgumentException e){System.out.println("Could not connect.");}// conexion is already closed, no matter what
Terminalbash
java ConTryWithResourcesConectando a servidor-datos...Enviando: SELECT * FROM productosConexión a servidor-datos cerrada.
When the problem belongs to your domain, standard exceptions do not describe it well.
SaldoInsuficienteException tells you what happened from its name.
Your own exception
When the problem belongs to your domain, standard exceptions do not describe it well. SaldoInsuficienteException tells you what happened from its name.
SaldoInsuficienteException.javajava
// Unchecked: the caller can prevent it by checking the balance firstpublicclassSaldoInsuficienteExceptionextendsRuntimeException{privatefinaldouble faltante;publicSaldoInsuficienteException(double solicitado,double disponible){super(String.format("Missing $%.2f: $%.2f requested and $%.2f available",solicitado - disponible, solicitado, disponible));this.faltante = solicitado - disponible;}publicdoublegetFaltante(){return faltante;}}
Notice that the exception carries data, not just a text.
The catch uses them: e.getFaltante() lets you decide what to show the user.
The exception carries data
Notice that the exception carries data, not just a text. The catch uses them: e.getFaltante() lets you decide what to show the user.
Retiro.javajava
try{cuenta.retirar(5000);}catch(SaldoInsuficienteException e){System.out.printf("You are short by $%.2f. Top up your balance?%n", e.getFaltante());}
The deciding question: can the caller do something reasonable to recover?
If it is an expected condition of the environment, extends Exception: checked.
If it is an API usage error, extends RuntimeException: unchecked, and the most common today.
Checked or unchecked?
The deciding question: can the caller do something reasonable to recover? If it is an expected condition of the environment, extends Exception: checked. If it is an API usage error, extends RuntimeException: unchecked, and the most common today.
When you translate a low-level exception into a domain one, never lose the original.
The second argument, e, is the cause: it stays stored inside the new exception.
That way the full stack trace remains available for debugging.
Chaining causes
When you translate a low-level exception into a domain one, never lose the original. The second argument, e, is the cause: it stays stored inside the new exception. That way the full stack trace remains available for debugging.
If you rethrow with e.getMessage() instead of e, the cause is lost.
The stack trace is cut right where the line that really failed was.
Without the cause, the trail is cut
If you rethrow with e.getMessage() instead of e, the cause is lost. The stack trace is cut right where the line that really failed was.
The empty catch: the exception goes in and vanishes without a trace.
The order was not saved, the user sees "done" and there is nothing in any log.
A swallowed error is infinitely worse than a visible one.
The empty catch
The empty catch: the exception goes in and vanishes without a trace. The order was not saved, the user sees "done" and there is nothing in any log. A swallowed error is infinitely worse than a visible one.
A return inside finally discards the exception that was traveling.
IllegalStateException is thrown, the finally does return 0 and nobody ever finds out.
return inside finally
A return inside finally discards the exception that was traveling. IllegalStateException is thrown, the finally does return 0 and nobody ever finds out.
The empty catch is the worst: it swallows the error and leaves no log at all.
Catching Exception up front also catches the bugs you wanted to blow up early.
Catch the most specific type you know how to handle.
The four antipatterns
The empty catch is the worst: it swallows the error and leaves no log at all. Catching Exception up front also catches the bugs you wanted to blow up early. Catch the most specific type you know how to handle.
A user not existing is not exceptional, it is just Tuesday.
Besides, throwing exceptions is expensive: building them means capturing the whole stack trace.
Exceptions as flow control
A user not existing is not exceptional, it is just Tuesday. Besides, throwing exceptions is expensive: building them means capturing the whole stack trace.
ControlDeFlujo.javajava
// Bad: uses an exception for something that happens every daytry{Usuario u =buscarUsuario(email);mostrar(u);}catch(UsuarioNoEncontradoException e){mostrarFormularioDeRegistro();}// Good: null expresses "there may be none" without any exceptionUsuario u =buscarUsuario(email);if(u !=null){mostrar(u);}else{mostrarFormularioDeRegistro();}
An empty catch, catch (Exception e) first and the general catch before the specific one.
Rethrowing with e.getMessage() instead of passing the cause, and fifty-line try blocks.
Closing resources by hand in finally and using exceptions for normal cases.
Common mistakes
An empty catch, catch (Exception e) first and the general catch before the specific one. Rethrowing with e.getMessage() instead of passing the cause, and fifty-line try blocks. Closing resources by hand in finally and using exceptions for normal cases.
Create EdadInvalidaException, a RuntimeException that stores the rejected age.
A registrar method throws it outside 0 to 120; another converts text and translates the error.
In main, try three cases and leave a record in a finally.
Challenge: age validation
Create EdadInvalidaException, a RuntimeException that stores the rejected age. A registrar method throws it outside 0 to 120; another converts text and translates the error. In main, try three cases and leave a record in a finally.
It is unchecked because the caller can validate the age first: it is a usage error.
The second constructor takes the cause to wrap another exception without losing it.
The domain exception
It is unchecked because the caller can validate the age first: it is a usage error. The second constructor takes the cause to wrap another exception without losing it.
EdadInvalidaException.javajava
publicclassEdadInvalidaExceptionextendsRuntimeException{privatefinalint edadRechazada;publicEdadInvalidaException(int edadRechazada){super("Invalid age: "+ edadRechazada +". It must be between 0 and 120.");this.edadRechazada = edadRechazada;}// Constructor with a cause: to wrap another exception without losing itpublicEdadInvalidaException(String mensaje,Throwable causa){super(mensaje, causa);this.edadRechazada =-1;}publicintgetEdadRechazada(){return edadRechazada;}}
registrar is the only place where the range rule lives.
registrarDesdeTexto translates the NumberFormatException but passes e as the cause.
registrar and registrarDesdeTexto
registrar is the only place where the range rule lives. registrarDesdeTexto translates the NumberFormatException but passes e as the cause.
RegistroDePersonas.javajava
publicclassRegistroDePersonas{privatestaticfinalintEDAD_MINIMA=0;privatestaticfinalintEDAD_MAXIMA=120;publicvoidregistrar(String nombre,int edad){if(nombre ==null|| nombre.isBlank()){thrownewIllegalArgumentException("The name is required");}if(edad <EDAD_MINIMA|| edad >EDAD_MAXIMA){thrownewEdadInvalidaException(edad);}System.out.println(" ✓ Registered: "+ nombre +", "+ edad +" years old");}publicvoidregistrarDesdeTexto(String nombre,String edadTexto){int edad;try{edad =Integer.parseInt(edadTexto.trim());}catch(NumberFormatException e){// We translate into OUR domain language, without losing the causethrownewEdadInvalidaException("'"+ edadTexto +"' is not a valid number for an age", e);}registrar(nombre, edad);// the range rule lives in a single place}}
A valid case, an out-of-range age and a text that is not a number.
The finally leaves a record in all three, and the technical cause is still available for the log.
Trying the three cases
A valid case, an out-of-range age and a text that is not a number. The finally leaves a record in all three, and the technical cause is still available for the log.
java MainRegistroIntentando registrar a Laura Giménez... ✓ Registrado: Laura Giménez, 28 años — intento finalizado —Intentando registrar a Carlos Ruiz... ✗ Edad inválida: 150. Debe estar entre 0 y 120. — intento finalizado —Intentando registrar a Ana Torres... ✗ 'treinta' no es un número válido para una edad causa técnica: java.lang.NumberFormatException: For input string: "treinta" — intento finalizado —
An exception is an object; unchecked is avoided, checked forces you to decide.
The finally always runs, the exception travels up the stack and try-with-resources closes for you.
When rethrowing, pass the cause, and remember: an empty catch is worse than not catching at all.
Takeaways
An exception is an object; unchecked is avoided, checked forces you to decide. The finally always runs, the exception travels up the stack and try-with-resources closes for you. When rethrowing, pass the cause, and remember: an empty catch is worse than not catching at all.