> For the complete documentation index, see [llms.txt](https://educacion.gitbook.io/programacion/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://educacion.gitbook.io/programacion/exercicios-java/ud4-solucions/excepcions.md).

# Excepcións

```java
// Excepción CHECKED - debe herdar de Exception
public class ExcepcionDNIInvalido extends Exception {
    
    // Construtor con mensaxe
    public ExcepcionDNIInvalido(String mensaxe) {
        super(mensaxe);
    }
    
    // Construtor por defecto
    public ExcepcionDNIInvalido() {
        super("DNI inválido: debe ter máximo 9 caracteres");
    }
}
```

```java
// Excepción UNCHECKED - debe herdar de RuntimeException
public class ExcepcionIdadeNegativa extends RuntimeException {
    
    public ExcepcionIdadeNegativa(String mensaxe) {
        super(mensaxe);
    }
    
    public ExcepcionIdadeNegativa() {
        super("Idade non pode ser negativa");
    }
}
```

```java
public class Persona {
    private String nome;
    private String dni;
    private int idade;
    
    // Construtor
    public Persona(String nome, String dni, int idade) 
            throws ExcepcionDNIInvalido {
        this.nome = nome;
        setDni(dni);        // Pode lanzar ExcepcionDNIInvalido (CHECKED)
        setIdade(idade);    // Pode lanzar ExcepcionIdadeNegativa (UNCHECKED)
    }
    
    // Método que require 'throws' porque lanza excepción CHECKED
    public void setDni(String dni) throws ExcepcionDNIInvalido {
        if (dni != null && dni.length() > 9) {
            throw new ExcepcionDNIInvalido(
                "DNI '" + dni + "' ten " + dni.length() + 
                " caracteres (máximo 9 permitidos)"
            );
        }
        this.dni = dni;
    }
    
    // Método que NON require 'throws' porque lanza excepción UNCHECKED
    public void setIdade(int idade) {
        if (idade < 0) {
            throw new ExcepcionIdadeNegativa(
                "Idade " + idade + " non é válida. Debe ser >= 0"
            );
        }
        this.idade = idade;
    }
    
    // Getters
    public String getNome() { return nome; }
    public String getDni() { return dni; }
    public int getIdade() { return idade; }
    
    @Override
    public String toString() {
        return "Persona{" + "nome='" + nome + '\'' + 
               ", dni='" + dni + '\'' + 
               ", idade=" + idade + '}';
    }
}
```

```java
public class MainPersona {
    
    public static void main(String[] args) {        
        Persona persona = null;       
        try {
            persona = new Persona("Carlos", "11111111A", 30);
            persona.setDni("123456789012");  // 12 caracteres > 9
            //persona.setIdade(-5);  // Isto lanzaría ExcepcionIdadeNegativa
            
        } catch (ExcepcionDNIInvalido e) {
            // PRIMEIRO CATCH: Excepción específica CHECKED
            System.out.println("   Mensaxe: " + e.getMessage());
        } catch (ExcepcionIdadeNegativa e) {
         // SEGUNDO CATCH: Excepción específica UNCHECKED  
            System.out.println("   Mensaxe: " + e.getMessage());
        } catch (Exception e) {
            // TERCEIRO CATCH: Excepción xerérica (captura calquera outra)
            System.out.println("   Mensaxe: " + e.getMessage());
        } finally {
            // FINALLY: Execútase SIEMPRE
            System.out.println("BLOQUE FINALLY - Execútase SIEMPRE");
        }
        // Continuación do programa despois do try-catch-finally
        System.out.println(persona)
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://educacion.gitbook.io/programacion/exercicios-java/ud4-solucions/excepcions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
