Skip to content

Commit

Permalink
feat(lang-enh): 🎸 try-with-resources, translated
Browse files Browse the repository at this point in the history
Refers: #4
  • Loading branch information
rcmoutinho committed Sep 11, 2019
1 parent 89dc92d commit f76ca26
Show file tree
Hide file tree
Showing 11 changed files with 100 additions and 102 deletions.
80 changes: 39 additions & 41 deletions book/02-language-enhancement/sections/02-try-with-resources.asc
Original file line number Diff line number Diff line change
@@ -1,132 +1,130 @@
:java-package: src/org/j6toj8/languageenhancements
:section-java-package: ../../../{java-package}

=== Try com recursos
=== Try-with-resources

.Objetivo
.Objective
----
Develop code that uses try-with-resources statements, including using classes that implement the AutoCloseable interface.
-
Desenvolver código que utilize instruções try-with-resources, incluindo o uso de classes que implementam a interface AutoCloseable.
----

É esperado que o candidato saiba compreender e analisar o uso da instrução _try-with-resources_, incluindo classes que implementam a interface `AutoClosable`.
The candidate is expected to understand and analyze the use of the _try-with-resources_ statement, including classes that implement the `AutoClosable` interface.

Antes de continuar, com base no exemplo a seguir, entenda a execução do método `main` e o que é apresentado no console após sua execução.
Before proceeding, based on the following example, understand the execution of the `main` method and what is presented on the console after its execution.

[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_Complete.java
----
include::{section-java-package}/trywithresources/TryWithResouces_Complete.java[tag=code]
----

O código acima utiliza dois arquivos, e faz leitura e escrita neles. A grande novidade desse código é a declaração de variáveis dentro de parênteses após a instrução `try`. Isso é a sintaxe chamada _try-with-resources_, e ela chama automaticamente o método `close()` dos recursos que estão sendo utilizados. Até o Java 6, seria necessário chamar o `close()` manualmente, como no exemplo abaixo.
The previous code uses two files and reads and writes them. The big news of this code is the declaration of variables within parentheses after the `try` statement. This is the syntax called _try-with-resources_, and it automatically calls the `close ()` method of the resources being used. Until Java 6, you would need to call `close ()` manually, as in the following example.

[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_Java6.java
----
include::{section-java-package}/trywithresources/TryWithResouces_Java6.java[tag=code]
----

. A instrução _try-with-resources_ fecha automaticamente os recursos que implementam a interface `AutoCloseable`.
. The _try-with-resources_ statement automatically closes resources that implement the `AutoCloseable` interface.

. Ela não precisa de `catch` nem `finally` explícitos.
. It does not need explicit `catch` or `finally`.
+
[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_AutoCloseable.java
----
include::{section-java-package}/trywithresources/TryWithResouces_AutoCloseable.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
try
Porta fechada.
Closed door.
----

. A instrução _try-with-resources_ ainda pode ter `catch` e `finally`, apesar de não ser necessário. Nesse caso, os recursos são fechados depois do `try` e antes de qualquer `catch` ou `finally`.
. The _try-with-resources_ statement can still have `catch` and `finally`, although it is not required. In this case, resources are closed after `try` and before either any `catch` or `finally`.

. O método `close` pode lançar uma exceção sendo capturada pelo `catch`, caso exista.
. The `close` method may throw an exception being caught by `catch`, if any.
+
[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_WithCatchFinally.java
----
include::{section-java-package}/trywithresources/TryWithResouces_WithCatchFinally.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
try
Porta fechada.
Closed door.
catch
finally
----
+
Ou seja, primeiro o `try` é chamado. Logo depois é chamado o método `close()` que ao final lança uma exceção. O `catch` captura essa exceção. E finalmente o `finally` é chamado.
That is, first the `try` is called. Soon after is called the `close ()` method which at the end throws an exception. `Catch` catches this exception. And finally `finally` is called.

. Os recursos declarados na instrução _try-with-resources_ são fechados na ordem inversa da declaração.
. Resources declared in the _try-with-resources_ statement are closed in the reverse order of the declaration.
+
[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_Order.java
----
include::{section-java-package}/trywithresources/TryWithResouces_Order.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
Olá.
Gaveta fechada.
Porta fechada.
Hello.
Drawer closed.
Closed door.
----
+
Ou seja, como a ordem de declaração dentro do _try-with-resources_ foi `Porta` e depois `Gaveta`, a ordem de chamada do método `close` é inversa: `Gaveta` e depois `Porta`.
That is, since the declaration order within _try-with-resources_ was `Door` and then `Drawer`, the call order of the `close` method is reversed: `Drawer` and then `Door`.

. Os recursos declarados no _try-with-resources_ só estão disponível dentro do bloco `try`.
. Resources declared in _try-with-resources_ are only available within the `try` block.
+
[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_ResourceInsideTry.java
----
include::{section-java-package}/trywithresources/TryWithResouces_ResourceInsideTry.java[tag=code]
----

. Somente classes que implementam `AutoCloseable` podem ser utilizadas dentro do _try-with-resources_.
. Only classes that implement `AutoCloseable` can be used within _try-with-resources_.
+
[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_NoAutoCloseable.java
----
include::{section-java-package}/trywithresources/TryWithResouces_NoAutoCloseable.java[tag=code]
----

. Caso o método `close()` lance uma exceção checada (ou seja, que herda de `Exception`), o código só compila se existir um `catch` que capture aquela exceção, ou o método declare o `throws`.
. If the `close ()` method throws a checked exception (i.e., inherits from `Exception`), the code only compiles if there is a `catch` that catches that exception or the method declares `throws`.
+
[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_CloseException.java
----
include::{section-java-package}/trywithresources/TryWithResouces_CloseException.java[tag=code]
----

. O Java 5 já possuía uma interface chamada `Closeable`, porém ela permite lançar apenas `IOException`. A nova interface `AutoCloseable` permite lançar qualquer exceção. Como `Closeable` atende a implementação de `AutoCloseable`, ela agora estende `AutoCloseable`. Logo, todas as classes que já implementavam `Closeable` podem ser utilizadas dentro do _try-with-resources_. Veja abaixo como era a interface `Closeable` antes e a partir do Java 7:
. Java 5 already had an interface called `Closeable`, but it allows only `IOException` to be thrown. The new `AutoCloseable` interface permits you to throw any exceptions. Since `Closeable` meets the implementation of `AutoCloseable`, it now extends `AutoCloseable`. So all classes that already implement `Closeable` can be used inside _try-with-resources_. Here's what the `Closeable` interface was like before and from Java 7:
+
.Antes do Java 7
.Before Java 7
[source,java]
----
public interface Closeable {
public void close() throws IOException;
}
----
+
.A partir do Java 7
.From Java 7
[source,java]
----
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
----

. Um comportamento novo são as exceções suprimidas (suppressed). Se ambos o bloco `try` e o método `close` lançam exceção, a do `close` fica suprimida, pois a do `try` é lançada primeiro.
. The new behavior is suppressed exceptions. If both the `try` block and the `close` method throw exception, that of `close` is suppressed because that of `try` is thrown first.
+
[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_Suppressed.java
Expand All @@ -139,38 +137,38 @@ include::{section-java-package}/trywithresources/TryWithResouces_Suppressed.java
----
try
close
erro no try
erro no close
error on try
error on close
----
+
Ou seja, a exceção que de fato foi capturada foi a do bloco `try`, pois foi lançada primeiro. A exceção lançada pelo método `close` ficou suprimida, e fica disponível em um array no método `getSuppressed()` da exceção.
That is, the exception that was actually caught was the `try` block because it was thrown first. The exception thrown by the `close` method has been suppressed and is available in an array in the exception `getSuppressed()` method.

. E por fim, é necessário lembrar que a instrução `try` "comum" ainda precisa obrigatoriamente de um `catch` ou `finally`.
. And lastly, it should be remembered that the _"default"_ `try` statement still necessarily needs a `catch` or `finally`.
+
[source,java,indent=0]
.{java-package}/trywithresources/TryWithResouces_CommonTry.java
----
include::{section-java-package}/trywithresources/TryWithResouces_CommonTry.java[tag=code]
----

==== Alguns tipos que implementam _Closeable_
==== Some types that implement _Closeable_

* `InputStream` e suas subclasses (`FileInputStream`, `ObjectInputStream`, etc)
* `OutputStream` e suas subclasses (`ByteArrayOutputStream`, `FileOutputStream`, etc)
* `Reader` e suas subclasses (`BufferedReader`, `CharSequenceReader`)
* `Writer` e suas subclasses (`BufferedWriter`, `PrintWriter`, etc)
* `InputStream` and its subclasses (`FileInputStream`, `ObjectInputStream`, etc)
* `OutputStream` and its subclasses (`ByteArrayOutputStream`, `FileOutputStream`, etc)
* `Reader` and its subclasses (`BufferedReader`, `CharSequenceReader`)
* `Writer` and its subclasses (`BufferedWriter`, `PrintWriter`, etc)

.Referências
.References
****
* Using Try-With-Resources
+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 296). Wiley. Edição do Kindle.
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 296). Wiley. Kindle Edition.
* https://www.baeldung.com/java-try-with-resources[Java – Try with Resources.]
* https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html[The try-with-resources Statement.] Java Documentation.
* https://pt.stackoverflow.com/questions/172909/como-funciona-o-try-with-resources/172910#172910[Como funciona o try-with-resources?]
* https://pt.stackoverflow.com/questions/172909/como-funciona-o-try-with-resources/172910#172910[Como funciona o try-with-resources?] (pt-BR)
****
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
public class TryWithResouces_AutoCloseable {

// tag::code[]
static class Porta implements AutoCloseable {
static class Door implements AutoCloseable {
@Override
public void close() { // chamado automaticamente pelo try-with-resources
System.out.println("Porta fechada.");
System.out.println("Closed door.");
}
}

public static void main(String[] args) throws FileNotFoundException {
try (Porta porta = new Porta()) { // Porta instanciada dentro da instrução try-with-resources
try (Door door = new Door()) { // Door instantiated within the try-with-resources statement
System.out.println("try");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,29 @@
public class TryWithResouces_CloseException {

// tag::code[]
static class Porta implements AutoCloseable {
static class Door implements AutoCloseable {
@Override
public void close() throws Exception { // declara throws Exception obrigatoriamente
public void close() throws Exception { // must declare throws Exception
throw new Exception();
}
}

void try1() {
try (Porta porta = new Porta()) { // NÃO COMPILA - exceção do close() não é capturada nem declarada
System.out.println("Olá 1");
try (Door door = new Door()) { // NOT COMPILING - the exception of close() is not captured or declared
System.out.println("Hello 1");
}
}

void try2() {
try (Porta porta = new Porta()) {
System.out.println("Olá 2");
} catch (Exception e) { // COMPILA - exceção capturada
try (Door door = new Door()) {
System.out.println("Hello 2");
} catch (Exception e) { // COMPILES - exception caught
}
}

void try3() throws Exception { // COMPILA - exceção declarada no método
try (Porta porta = new Porta()) {
System.out.println("Olá 3");
void try3() throws Exception { // COMPILES - exception declared in the method
try (Door door = new Door()) {
System.out.println("Hello 3");
}
}
// end::code[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,23 @@ public class TryWithResouces_CommonTry {
public static void main(String[] args) {
try {
System.out.println("try");
} // NÃO COMPILA - try "comum" sem catch ou finally
} // NOT COMPILING - "common" try without catch or finally

try {
System.out.println("try");
} catch (Exception e) {
} // COMPILA - try "comum" só com catch
} // COMPILES - "common" try with catch only

try {
System.out.println("try");
} finally {
} // COMPILA - try "comum" só com finally
} // COMPILES - "common" try with finally only

try {
System.out.println("try");
} catch (Exception e) {
} finally {
} // COMPILA - try "comum" com catch e finally
} // COMPILES - "common" try with catch and finally
}
// end::code[]
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,35 +11,35 @@ public class TryWithResouces_Complete {

// tag::code[]
public static void main(String[] args) throws IOException {
// criação de 2 arquivos
File file = new File("arquivo.txt");
File file2 = new File("arquivo2.txt");
// creates 2 files
File file = new File("file.txt");
File file2 = new File("file2.txt");

// Exemplo try-with-resources com PrintWriter
// try-with-resources example with PrintWriter
try (PrintWriter writer = new PrintWriter(file)) {
// escreve no arquivo.txt
writer.println("Olá Mundo!");
// write to file.txt
writer.println("Hello World!");
}

// Exemplo try-with-resources com BufferedReader
// try-with-resources example with BufferedReader
try (BufferedReader reader = Files.newBufferedReader(file.toPath())) {
// imprime no console uma linha do arquivo.txt
// print a line from file.txt to the console
System.out.println(reader.readLine());
}

// Exemplo try-with-resources com BufferedReader e BufferedWriter
// try-with-resources example with BufferedReader and BufferedWriter
try (BufferedReader reader = Files.newBufferedReader(file.toPath());
BufferedWriter writer = Files.newBufferedWriter(file2.toPath())) {
// lê a linha do arquivo.txt e escreve no arquivo2.txt
// read line from file.txt and write to file2.txt
writer.write(reader.readLine() + "2");
}

// Exemplo try-with-resources com BufferedReader
// try-with-resources example with BufferedReader
try (BufferedReader reader = Files.newBufferedReader(file2.toPath())) {
// imprime no console uma linha do arquivo2.txt
// print a line from file2.txt to the console
System.out.println(reader.readLine());
}
// todos os Reader e Writer já foram fechados.
// all Reader and Writer have already been closed
}
// end::code[]
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ public class TryWithResouces_Java6 {

// tag::code[]
public static void main(String[] args) throws FileNotFoundException {
File file = new File("arquivo.txt");
File file = new File("file.txt");
PrintWriter writer = null;
try {
writer = new PrintWriter(file);
writer.println("Olá Mundo!");
writer.println("Hello World!");
} finally {
if (writer != null) {
writer.close(); // fechando o writer manualmente
writer.close(); // closing the writer manually
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
public class TryWithResouces_NoAutoCloseable {

// tag::code[]
static class Prateleira {}
static class Shelf {}

public static void main(String[] args) {
try (Prateleira prateleira = new Prateleira()) { // NÃO COMPILA - Prateleira não implementa AutoClosable
System.out.println("Olá");
try (Shelf shelf = new Shelf()) { // NOT COMPILING - Shelf do not implement AutoCloseable
System.out.println("Hello");
}
}
// end::code[]
Expand Down
Loading

0 comments on commit f76ca26

Please sign in to comment.