Manejo de Excepciones en Java: Try-Catch-Finally, Throw, Throws y Excepciones Personalizadas
Este artículo es una guía completa sobre el manejo de excepciones en Java, incluyendo try-catch-finally, throw, throws y excepciones personalizadas con ejemplos prácticos.
En Resumen
El manejo de excepciones permite controlar los errores en Java de forma estructurada. Try-catch-finally captura excepciones, throw y throws las declaran o lanzan, y las excepciones personalizadas permiten un tratamiento de errores específico.
Descripción Técnica Compacta
El manejo de excepciones es un mecanismo para gestionar errores y condiciones anómalas durante la ejecución del programa. Java utiliza una jerarquía estructurada de excepciones.
Jerarquía de excepciones:
- Throwable: Clase base de todos los errores y excepciones
- Error: Errores graves del sistema (no recuperables)
- Exception: Excepciones recuperables
- Checked Exceptions: Verificación obligatoria en tiempo de compilación
- Unchecked Exceptions: Errores en tiempo de ejecución (RuntimeException)
Conceptos clave:
Try-Catch-Finally
- try: Bloque con código que puede generar errores
- catch: Bloque para capturar excepciones específicas
- finally: Bloque que siempre se ejecuta (incluso con excepciones)
- try-with-resources: Liberación automática de recursos
Throw y Throws
- throw: Lanzamiento explícito de una excepción
- throws: Declaración de excepciones en la firma del método
- rethrow: Relanzamiento de excepciones
Excepciones Personalizadas
- Clases Exception propias: Manejo de errores específicos
- Business Exceptions: Errores del dominio de la aplicación
- Validation Exceptions: Errores de validación de entrada
Puntos Clave para Evaluación
- Manejo de excepciones: Tratamiento estructurado de errores en Java
- Try-Catch-Finally: Bloques fundamentales de tratamiento de errores
- Checked vs Unchecked Exceptions: Errores en tiempo de compilación vs ejecución
- Throw vs Throws: Lanzamiento vs declaración de excepciones
- Excepciones personalizadas: Crear clases Exception propias
- Jerarquía de excepciones: Throwable → Error/Exception → RuntimeException
- Relevante para certificación: Esencial para escribir software robusto y resiliente
Componentes Principales
- Jerarquía de excepciones: Throwable, Error, Exception, RuntimeException
- Try-Catch-Finally: Estructura de manejo de errores
- Throw/Throws: Lanzamiento y declaración de excepciones
- Excepciones personalizadas: Clases de error específicas
- Try-with-Resources: Gestión automática de recursos
- Exception Chaining: Encadenamiento de excepciones
- Buenas prácticas: Directrices para el manejo de excepciones
- Logging: Registro de errores
Ejemplos Prácticos
1. Manejo Básico de Excepciones
import java.io.*;
import java.util.*;
public class ExceptionGrundlagen {
public static void main(String[] args) {
System.out.println("=== Exception Handling Grundlagen ===");
// Einfache try-catch
einfachesTryCatch();
// Mehrere catch-Blöcke
mehrfachCatch();
// Finally-Block
finallyDemo();
// Try-with-Resources
tryWithResourcesDemo();
// Exception-Auslösung
exceptionAusloesen();
}
private static void einfachesTryCatch() {
System.out.println("\n--- Einfaches Try-Catch ---");
try {
// Potentiell fehlerhafter Code
int ergebnis = 10 / 0; // ArithmeticException
System.out.println("Ergebnis: " + ergebnis);
} catch (ArithmeticException e) {
System.out.println("Fehler: Division durch Null");
System.out.println("Exception-Typ: " + e.getClass().getSimpleName());
System.out.println("Nachricht: " + e.getMessage());
}
System.out.println("Programm läuft weiter");
}
private static void mehrfachCatch() {
System.out.println("\n--- Mehrfache Catch-Blöcke ---");
String[] zahlen = {"10", "5", "abc", "2"};
for (String zahlString : zahlen) {
try {
int zahl = Integer.parseInt(zahlString);
int ergebnis = 100 / zahl;
System.out.println("100 / " + zahl + " = " + ergebnis);
} catch (NumberFormatException e) {
System.out.println("Fehler: '" + zahlString + "' ist keine Zahl");
} catch (ArithmeticException e) {
System.out.println("Fehler: Division durch Null bei " + zahlString);
} catch (Exception e) {
// Allgemeiner Exception-Handler
System.out.println("Unerwarteter Fehler: " + e.getMessage());
}
}
}
private static void finallyDemo() {
System.out.println("\n--- Finally-Block Demo ---");
BufferedReader reader = null;
try {
// Ressource öffnen
reader = new BufferedReader(new FileReader("nichtexistente.txt"));
String zeile = reader.readLine();
System.out.println("Gelesen: " + zeile);
} catch (FileNotFoundException e) {
System.out.println("Datei nicht gefunden: " + e.getMessage());
} catch (IOException e) {
System.out.println("Lesefehler: " + e.getMessage());
} finally {
// Wird immer ausgeführt
System.out.println("Finally-Block wird ausgeführt");
if (reader != null) {
try {
reader.close();
System.out.println("Reader geschlossen");
} catch (IOException e) {
System.out.println("Fehler beim Schließen: " + e.getMessage());
}
}
}
}
private static void tryWithResourcesDemo() {
System.out.println("\n--- Try-with-Resources Demo ---");
// Automatische Ressourcenverwaltung
try (BufferedReader reader = new BufferedReader(new FileReader("beispiel.txt"))) {
String zeile;
int zeilenNummer = 1;
while ((zeile = reader.readLine()) != null) {
System.out.println("Zeile " + zeilenNummer + ": " + zeile);
zeilenNummer++;
if (zeilenNummer > 3) {
throw new IOException("Künstlicher Fehler nach 3 Zeilen");
}
}
} catch (FileNotFoundException e) {
System.out.println("Datei nicht gefunden: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO-Fehler: " + e.getMessage());
} finally {
System.out.println("Try-with-Resources beendet (Reader automatisch geschlossen)");
}
}
private static void exceptionAusloesen() {
System.out.println("\n--- Exception-Auslösung ---");
try {
validiereAlter(15); // Löst Exception aus
} catch (IllegalArgumentException e) {
System.out.println("Validierungsfehler: " + e.getMessage());
}
try {
validiereAlter(25); // Kein Fehler
} catch (IllegalArgumentException e) {
System.out.println("Dies sollte nicht passieren: " + e.getMessage());
}
System.out.println("Alter-Validierung abgeschlossen");
}
private static void validiereAlter(int alter) {
if (alter < 18) {
throw new IllegalArgumentException("Alter muss mindestens 18 sein, aber war: " + alter);
}
System.out.println("Alter " + alter + " ist gültig");
}
}
2. Excepciones personalizadas y cláusula throws
// Clases de Exception personalizadas
class GeschaeftsException extends Exception {
public GeschaeftsException(String nachricht) {
super(nachricht);
}
public GeschaeftsException(String nachricht, Throwable ursache) {
super(nachricht, ursache);
}
}
class ValidierungsException extends RuntimeException {
private String feld;
public ValidierungsException(String feld, String nachricht) {
super(nachricht);
this.feld = feld;
}
public String getFeld() {
return feld;
}
}
class DatenbankException extends Exception {
private int fehlercode;
public DatenbankException(String nachricht, int fehlercode) {
super(nachricht);
this.fehlercode = fehlercode;
}
public int getFehlercode() {
return fehlercode;
}
}
// Clases Service con Exception Handling
class KundenService {
// Método con cláusula throws
public Kunde findeKunde(int kundenId) throws GeschaeftsException, DatenbankException {
try {
// Simula acceso a base de datos
if (kundenId < 1000) {
throw new DatenbankException("Ungültige Kunden-ID: " + kundenId, 404);
}
if (kundenId == 1234) {
throw new DatenbankException("Datenbankverbindung fehlgeschlagen", 500);
}
// Simula acceso exitoso
return new Kunde(kundenId, "Max Mustermann", "max@example.com");
} catch (SQLException e) {
// Exception Chaining - preserva la Exception original
throw new DatenbankException("Datenbankfehler bei Kundensuche", 503);
}
}
// Método con Exception personalizada
public void kundeAnlegen(Kunde kunde) throws GeschaeftsException {
try {
validiereKunde(kunde);
// Simula lógica de negocio
if (kunde.getName().toLowerCase().contains("test")) {
throw new GeschaeftsException("Test-Kunden dürfen nicht angelegt werden");
}
// El cliente se guardaría en base de datos aquí
System.out.println("Kunde angelegt: " + kunde.getName());
} catch (ValidierungsException e) {
// Re-throw con información adicional
throw new GeschaeftsException("Kundendaten ungültig: " + e.getMessage(), e);
}
}
private void validiereKunde(Kunde kunde) {
if (kunde.getName() == null || kunde.getName().trim().isEmpty()) {
throw new ValidierungsException("name", "Name darf nicht leer sein");
}
if (kunde.getEmail() == null || !kunde.getEmail().contains("@")) {
throw new ValidierungsException("email", "Ungültige E-Mail-Adresse");
}
if (kunde.getName().length() > 100) {
throw new ValidierungsException("name", "Name zu lang (max 100 Zeichen)");
}
}
}
// Modelo de datos
class Kunde {
private int id;
private String name;
private String email;
public Kunde(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// Getter
public int getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
}
// Clase principal para demostración
public class CustomExceptionDemo {
public static void main(String[] args) {
System.out.println("=== Custom Exceptions Demo ===");
KundenService service = new KundenService();
// Demo 1: Búsqueda de cliente exitosa
try {
Kunde kunde = service.findeKunde(1001);
System.out.println("Kunde gefunden: " + kunde.getName());
} catch (GeschaeftsException | DatenbankException e) {
System.out.println("Fehler bei Kundensuche: " + e.getMessage());
}
// Demo 2: Error de base de datos
try {
service.findeKunde(999);
} catch (GeschaeftsException e) {
System.out.println("Geschäftsfehler: " + e.getMessage());
} catch (DatenbankException e) {
System.out.println("Datenbankfehler (Code " + e.getFehlercode() + "): " + e.getMessage());
}
// Demo 3: Error de validación al crear
try {
Kunde ungueltigerKunde = new Kunde(0, "", "ungueltig@");
service.kundeAnlegen(ungueltigerKunde);
} catch (GeschaeftsException e) {
System.out.println("Fehler beim Kundenanlegen: " + e.getMessage());
// Mostrar Exception original
if (e.getCause() instanceof ValidierungsException) {
ValidierungsException ve = (ValidierungsException) e.getCause();
System.out.println("Validierungsfehler in Feld '" + ve.getFeld() + "'");
}
}
// Demo 4: Exception de regla de negocio
try {
Kunde testKunde = new Kunde(0, "Test User", "test@example.com");
service.kundeAnlegen(testKunde);
} catch (GeschaeftsException e) {
System.out.println("Business Rule Fehler: " + e.getMessage());
}
// Demo 5: Logging de Exceptions
exceptionLoggingDemo();
}
private static void exceptionLoggingDemo() {
System.out.println("\n--- Exception Logging Demo ---");
try {
// Simula operación compleja
komplexeOperation();
} catch (Exception e) {
// Logging estructurado
logException(e);
}
}
private static void komplexeOperation() throws Exception {
try {
// Primera operación
ersteOperation();
// Segunda operación
zweiteOperation();
} catch (IllegalArgumentException e) {
// Propaga Exception con información de contexto
throw new Exception("Fehler in komplexer Operation", e);
}
}
private static void ersteOperation() {
if (Math.random() > 0.5) {
throw new IllegalArgumentException("Fehler in erster Operation");
}
System.out.println("Erste Operation erfolgreich");
}
private static void zweiteOperation() {
if (Math.random() > 0.7) {
throw new IllegalArgumentException("Fehler in zweiter Operation");
}
System.out.println("Zweite Operation erfolgreich");
}
private static void logException(Exception e) {
System.out.println("=== Exception Log ===");
System.out.println("Typ: " + e.getClass().getSimpleName());
System.out.println("Nachricht: " + e.getMessage());
System.out.println("Stack Trace:");
// Imprime Stack Trace
for (StackTraceElement element : e.getStackTrace()) {
System.out.println(" at " + element.getClassName() +
"." + element.getMethodName() +
"(" + element.getFileName() +
":" + element.getLineNumber() + ")");
}
// Registra Exception original
if (e.getCause() != null) {
System.out.println("Ursache: " + e.getCause().getClass().getSimpleName() +
" - " + e.getCause().getMessage());
}
}
}
3. Patrones avanzados de manejo de excepciones
import java.util.*;
import java.util.function.*;
public class AdvancedExceptionPatterns {
// Result Pattern para manejo de errores sin excepciones
static class Result<T> {
private final T value;
private final Exception error;
private final boolean success;
private Result(T value, Exception error, boolean success) {
this.value = value;
this.error = error;
this.success = success;
}
public static <T> Result<T> success(T value) {
return new Result<>(value, null, true);
}
public static <T> Result<T> failure(Exception error) {
return new Result<>(null, error, false);
}
public boolean isSuccess() { return success; }
public boolean isFailure() { return !success; }
public T getValue() {
if (!success) {
throw new IllegalStateException("No hay valor disponible en caso de error");
}
return value;
}
public Exception getError() {
if (success) {
throw new IllegalStateException("No hay error en caso de éxito");
}
return error;
}
public <U> Result<U> map(Function<T, U> mapper) {
if (success) {
try {
return Result.success(mapper.apply(value));
} catch (Exception e) {
return Result.failure(e);
}
} else {
return Result.failure(error);
}
}
public <U> Result<U> flatMap(Function<T, Result<U>> mapper) {
if (success) {
try {
return mapper.apply(value);
} catch (Exception e) {
return Result.failure(e);
}
} else {
return Result.failure(error);
}
}
public T orElse(T defaultValue) {
return success ? value : defaultValue;
}
}
// Wrappers de excepciones para Functional Interfaces
@FunctionalInterface
interface CheckedSupplier<T> {
T get() throws Exception;
}
@FunctionalInterface
interface CheckedRunnable {
void run() throws Exception;
}
@FunctionalInterface
interface CheckedFunction<T, R> {
R apply(T t) throws Exception;
}
// Métodos utilitarios para manejo de excepciones
static class ExceptionUtils {
public static <T> Optional<T> optionalOf(CheckedSupplier<T> supplier) {
try {
return Optional.ofNullable(supplier.get());
} catch (Exception e) {
return Optional.empty();
}
}
public static <T> Result<T> resultOf(CheckedSupplier<T> supplier) {
try {
return Result.success(supplier.get());
} catch (Exception e) {
return Result.failure(e);
}
}
public static void unchecked(CheckedRunnable runnable) {
try {
runnable.run();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T, R> Function<T, R> uncheckedFunction(CheckedFunction<T, R> function) {
return t -> {
try {
return function.apply(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
public static <T> Supplier<T> uncheckedSupplier(CheckedSupplier<T> supplier) {
return () -> {
try {
return supplier.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
}
// Mecanismo de reintentos
static class RetryUtils {
public static <T> T retry(int maxAttempts, long delayMs, CheckedSupplier<T> supplier)
throws Exception {
Exception lastException = null;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return supplier.get();
} catch (Exception e) {
lastException = e;
if (attempt == maxAttempts) {
break;
}
System.out.println("Intento " + attempt + " falló, reintentando en " + delayMs + "ms");
Thread.sleep(delayMs);
}
}
throw new Exception("Los " + maxAttempts + " intentos fallaron", lastException);
}
public static <T> Optional<T> retryOptional(int maxAttempts, long delayMs,
CheckedSupplier<T> supplier) {
try {
return Optional.of(retry(maxAttempts, delayMs, supplier));
} catch (Exception e) {
return Optional.empty();
}
}
}
// Clases de servicio con patrones avanzados
static class DatenbankService {
// Con Result Pattern
public Result<String> leseDatenMitResult(String id) {
try {
// Simula acceso a la base de datos
if (id == null || id.isEmpty()) {
return Result.failure(new IllegalArgumentException("El ID no puede estar vacío"));
}
if (id.equals("error")) {
return Result.failure(new RuntimeException("Error en la base de datos"));
}
String daten = "Datos para " + id;
return Result.success(daten);
} catch (Exception e) {
return Result.failure(e);
}
}
// Con Optional
public Optional<String> leseDatenMitOptional(String id) {
return ExceptionUtils.optionalOf(() -> {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("El ID no puede estar vacío");
}
if (id.equals("notfound")) {
return null;
}
return "Datos para " + id;
});
}
// Con Retry
public String leseDatenMitRetry(String id) throws Exception {
return RetryUtils.retry(3, 1000, () -> {
// Simula conexión inestable
if (Math.random() > 0.7) {
throw new RuntimeException("Error de conexión");
}
return "Datos estables para " + id;
});
}
}
public static void main(String[] args) {
System.out.println("=== Patrones avanzados de manejo de excepciones ===");
DatenbankService service = new DatenbankService();
// Demo del Result Pattern
System.out.println("\n--- Demo del Result Pattern ---");
Result<String> result1 = service.leseDatenMitResult("123");
System.out.println("Exitoso: " + result1.isSuccess());
result1.ifPresent(value -> System.out.println("Valor: " + value));
Result<String> result2 = service.leseDatenMitResult("error");
System.out.println("Exitoso: " + result2.isSuccess());
result2.ifPresentOrElse(
value -> System.out.println("Valor: " + value),
error -> System.out.println("Error: " + error.getMessage())
);
// Encadenamiento de Result
Result<Integer> laenge = result1
.map(String::length)
.map(laeng -> laeng * 2);
System.out.println("Longitud duplicada: " + laenge.orElse(0));
// Demo del Optional Pattern
System.out.println("\n--- Demo del Optional Pattern ---");
Optional<String> opt1 = service.leseDatenMitOptional("123");
opt1.ifPresent(daten -> System.out.println("Encontrado: " + daten));
Optional<String> opt2 = service.leseDatenMitOptional("notfound");
System.out.println("Encontrado: " + opt2.isPresent());
// Optional con valor por defecto
String ergebnis = opt2.orElse("Valor por defecto");
System.out.println("Resultado: " + ergebnis);
// Demo del Retry
System.out.println("\n--- Demo del Retry ---");
try {
String daten = service.leseDatenMitRetry("123");
System.out.println("Éxito tras reintentos: " + daten);
} catch (Exception e) {
System.out.println("Todos los reintentos fallaron: " + e.getMessage());
}
// Demo de Exception Utils
System.out.println("\n--- Demo de Exception Utils ---");
// Unchecked Functional Interface
List<String> zahlen = Arrays.asList("10", "5", "abc", "2");
zahlen.stream()
.map(ExceptionUtils.uncheckedFunction(zahl -> Integer.parseInt(zahl) * 2))
.forEach(ergebnis -> System.out.println("Duplicado: " + ergebnis));
// Logging de excepciones con contexto
System.out.println("\n--- Excepción con contexto ---");
try {
berechneKomplex(10, 0);
} catch (Exception e) {
logWithContext(e, Map.of(
"operation", "berechneKomplex",
"param1", 10,
"param2", 0,
"timestamp", System.currentTimeMillis()
));
}
}
private static int berechneKomplex(int a, int b) throws Exception {
if (b == 0) {
throw new ArithmeticException("División entre cero");
}
return a / b;
}
private static void logWithContext(Exception e, Map<String, Object> context) {
System.out.println("=== Excepción con contexto ===");
System.out.println("Excepción: " + e.getClass().getSimpleName());
System.out.println("Mensaje: " + e.getMessage());
System.out.println("Contexto:");
context.forEach((key, value) ->
System.out.println(" " + key + ": " + value));
System.out.println("Stack Trace:");
Arrays.stream(e.getStackTrace())
.limit(3)
.forEach(element ->
System.out.println(" at " + element.getClassName() +
"." + element.getMethodName()));
}
// Método auxiliar para Result
private static <T> void ifPresent(Result<T> result, Consumer<T> action) {
if (result.isSuccess()) {
action.accept(result.getValue());
}
}
}
Jerarquía de excepciones
Throwable
├── Error (Errores del sistema, no tratables)
│ ├── OutOfMemoryError
│ ├── StackOverflowError
│ └── VirtualMachineError
└── Exception (Excepciones tratables)
├── Checked Exceptions (Verificación en tiempo de compilación)
│ ├── IOException
│ │ ├── FileNotFoundException
│ │ └── SQLException
│ ├── ClassNotFoundException
│ └── InterruptedException
└── RuntimeException (Unchecked Exceptions)
├── NullPointerException
├── IllegalArgumentException
├── ArithmeticException
├── IndexOutOfBoundsException
└── NumberFormatException
Buenas prácticas en manejo de excepciones
Lo que debes hacer
- Capturar excepciones específicas: En lugar de atrapar siempre
Exception - Limpiar recursos: Usa finally o try-with-resources
- Mensajes significativos: Descripción clara del error
- Encadenamiento de excepciones: Preserva la excepción original
- Logging: Registra excepciones con contexto
Lo que debes evitar
- Bloques catch vacíos: Ignorar excepciones
- Suprimir excepciones: Ocultar errores sin tratarlos
- Capturar demasiado genérico: Excepciones muy amplias
- Devolver null: Usa Optional o Result en su lugar
- printStackTrace: En código de producción
Try-with-resources versus finally
Try-with-resources (Moderno)
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
// Los recursos se cierran automáticamente
} catch (IOException e) {
// Manejo de la excepción
}
Bloque finally (Tradicional)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("file.txt"));
// Trabajar con reader
} catch (IOException e) {
// Manejo de la excepción
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Manejar error al cerrar
}
}
}
Patrones de manejo de excepciones
Template Method Pattern
public abstract class DatabaseTemplate {
public final Result<T> execute(CheckedSupplier<T> operation) {
try {
Connection conn = getConnection();
try {
return Result.success(operation.get());
} finally {
conn.close();
}
} catch (Exception e) {
return Result.failure(e);
}
}
protected abstract Connection getConnection() throws SQLException;
}
Decorator Pattern
public class RetryDecorator<T> implements Supplier<T> {
private final Supplier<T> supplier;
private final int maxRetries;
public RetryDecorator(Supplier<T> supplier, int maxRetries) {
this.supplier = supplier;
this.maxRetries = maxRetries;
}
@Override
public T get() {
Exception lastException = null;
for (int i = 0; i <= maxRetries; i++) {
try {
return supplier.get();
} catch (Exception e) {
lastException = e;
if (i < maxRetries) {
// Esperar antes de reintentar
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException(ie);
}
}
}
}
throw new RuntimeException("All retries failed", lastException);
}
}
Ventajas y desventajas
Ventajas del manejo de excepciones
- Control de errores: Tratamiento estructurado de fallos
- Claridad del código: Separación entre flujo normal y casos de error
- Robustez: Programas estables incluso frente a errores
- Debugging: Mejor análisis de fallos mediante stack traces
- Mantenibilidad: Manejo centralizado de errores
Desventajas
- Performance: El manejo de excepciones tiene sobrecarga
- Complejidad: Estructuras try-catch anidadas
- Overhead: Más código para gestionar errores
- Abuso: Usar excepciones para controlar el flujo
Preguntas frecuentes en exámenes
-
¿Cuál es la diferencia entre excepciones checked y unchecked? Las excepciones checked deben declararse o tratarse, las unchecked no (RuntimeException).
-
¿Cuándo se ejecuta finally? Siempre, independientemente de si ocurre una excepción o no, incluso si hay return en el bloque try.
-
¡Explica try-with-resources! Cierre automático de recursos para objetos que implementan AutoCloseable.
-
¿Qué es encadenamiento de excepciones? Pasar excepciones adelante mientras se preserva la causa original.
Fuentes más importantes
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- https://www.baeldung.com/java-exceptions
- https://effectivejava.com/



