> 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/ud5-entrada-e-saida-da-informacion/ficheiros/excepciones-entrada-saida/try-with-resources.md).

# Try-with-resources

O **`try-with-resources`** é unha forma de xestionar recursos que implementan a interface **`AutoCloseable`** (como ficheiros, fluxos de entrada/saída ou conexións de base de datos), garantindo que **se pechen automaticamente** ao final do bloque, incluso se ocorre unha excepción.

```java
try (Resource r = new Resource()) {
    // usar o recurso
} catch (Exception e) {
    // xestionar excepción
}
```

## ¿Por que empregalo?

* Evita **fugas de recursos** (como esquecer pechar un ficheiro).
* O recurso **pechase automaticamente** ao saír do bloque `try`.
* Reduce a cantidade de código, eliminando a necesidade de `finally`.
* Funciona con **calquera clase que implemente AutoCloseable**

## Exemplo con BufferedReader

```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class EjemploTryWithResources {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("fichero.txt"))) {
            String linea;
            while ((linea = br.readLine()) != null) {
                System.out.println(linea);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```


---

# 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/ud5-entrada-e-saida-da-informacion/ficheiros/excepciones-entrada-saida/try-with-resources.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.
