← Java EspañolChapter 11 of 13

Manejo de Excepciones

## Objetivos de Aprendizaje - Comprender los tipos de excepciones - Usar try, catch, finally - Lanzar excepciones personalizadas - Manejar excepciones gracefulmente ## ¿Qué es una Excepción? Un evento que interrumpe el flujo normal del programa: ```java public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); // ¡ArrayIndexOutOfBoundsException! } } ``` ## Jerarquía de Excepciones ```text Throwable ├── Error (sistema, irrecuperable) │ ├── OutOfMemoryError │ └── StackOverflowError └── Exception (recuperable) ├── RuntimeException (no verificada) │ ├── NullPointerException │ ├── ArrayIndexOutOfBoundsException │ └── ArithmeticException └── Otras (verificada) ├── IOException └── SQLException ``` ## Try-Catch ### Sintaxis Básica ```java try { int result = 10 / 0; // Podría lanzar } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } ``` ### Múltiples Catch ```java try { int[] arr = new int[5]; arr[10] = 100; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index error!"); } catch (ArithmeticException e) { System.out.println("Math error!"); } catch (Exception e) { System.out.println("Generic error: " + e.getMessage()); } ``` ### Orden de Catch Lo más específico primero, luego lo general: ```java try { // código } catch (NullPointerException e) { // Específico primero // manejar } catch (RuntimeException e) { // Luego más general // manejar } catch (Exception e) { // Finalmente, lo más general // manejar } ``` ## Bloque Finally ### Siempre Se Ejecuta ```java Scanner scanner = new Scanner(System.in); try { System.out.print("Enter number: "); int num = Integer.parseInt(scanner.nextLine()); System.out.println("Result: " + 10 / num); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Closing scanner"); scanner.close(); // ¡Siempre se ejecuta! } ``` ### Try-with-resources (Java 7+) ```java try (Scanner scanner = new Scanner(System.in)) { int num = Integer.parseInt(scanner.nextLine()); System.out.println("Result: " + 10 / num); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } // Scanner cerrado automáticamente ``` ## Lanzando Excepciones ### Palabra Clave throw ```java public static void validateAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } if (age > 150) { throw new IllegalArgumentException("Age is too high"); } } ``` ### Tipos de Excepciones | Tipo | Cuándo Lanzar | |------|---------------| | IllegalArgumentException | Argumento inválido | | IllegalStateException | Estado inválido | | NullPointerException | valor null donde no está permitido | | IndexOutOfBoundsException | Índice fuera de rango | | UnsupportedOperationException | Operación no soportada | ## Excepciones Personalizadas ### Definir Clase de Excepción ```java public class ValidationException extends Exception { public ValidationException(String message) { super(message); } } public class InvalidEmailException extends ValidationException { public InvalidEmailException(String email) { super("Invalid email: " + email); } } ``` ### Usando Excepción Personalizada ```java public static void registerUser(String email) throws ValidationException { if (!email.contains("@")) { throw new InvalidEmailException(email); } // lógica de registro } ``` ## Verificadas vs No Verificadas ### Excepciones Verificadas Deben manejarse o declararse: ```java public void readFile() throws IOException { FileReader reader = new FileReader("file.txt"); // Debe manejar IOException reader.close(); } ``` ### Excepciones No Verificadas No hay requisito de manejar: ```java public void accessArray() { int[] arr = {1, 2, 3}; arr[10] = 5; // RuntimeException - puede pero no tiene que manejar } ``` ## Tipos Comunes de Excepciones ```java // NullPointerException String str = null; str.length(); // NPE // ArrayIndexOutOfBoundsException int[] arr = {1, 2}; arr[5] = 10; // AIOOBE // ArithmeticException int x = 10 / 0; // División por cero // ClassCastException Object obj = "hello"; Integer num = (Integer) obj; // CCE // NumberFormatException int num = Integer.parseInt("abc"); // NFE ``` ## Métodos de Excepciones ```java try { riskyOperation(); } catch (Exception e) { e.getMessage(); // Descripción breve e.getCause(); // Excepción causante e.printStackTrace(); // Traza completa de la pila } ``` ## Mejores Prácticas ### Hacer ```java // Capturar excepciones específicas try { FileReader reader = new FileReader("file.txt"); } catch (FileNotFoundException e) { // Manejar excepción específica } // Limpiar recursos try (FileReader reader = new FileReader("file.txt")) { // usar reader } // Registrar y relanzar try { doSomething(); } catch (Exception e) { logger.error("Failed", e); throw e; } ``` ### No Hacer ```java // No tragar excepciones try { doSomething(); } catch (Exception e) { // ¡No hacer nada oculta errores! } // No capturar Throwable try { doSomething(); } catch (Throwable t) { // ¡Captura todo incluyendo Errors! // ¡Demasiado amplio! } ``` ## Resumen - Las excepciones interrumpen el flujo normal - try-catch-finally maneja excepciones - finally siempre se ejecuta (usar try-with-resources) - throw lanza una excepción; throws declara excepción - Las excepciones personalizadas extienden Exception - Verificadas: deben manejarse; No verificadas: opcional - Capturar excepciones específicas primero - Nunca tragar excepciones silenciosamente

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →