Exceptions and error handling, step by step

The file is missing

FileNotFoundException

The network drops

SocketException

The user types "twenty-two"

NumberFormatException

The database refuses the connection

SQLException

What does your code do when it fails?

try

It is cut at the line that fails

catch

Runs only if the type matches

finally

Always runs, even with a return

What follows

The program continues normally

Unchecked · RuntimeException

Programming errors

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

CursoDeJava · l12_excepciones_y_manejo_de_errores

16 exercises: from the unchecked division to custom exceptions