You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Develop code that uses try-with-resources statements, including using classes that implement the AutoCloseable interface.
9
-
-
10
-
Desenvolver código que utilize instruções try-with-resources, incluindo o uso de classes que implementam a interface AutoCloseable.
11
9
----
12
10
13
-
É esperado que o candidato saiba compreender e analisar o uso da instrução _try-with-resources_, incluindo classes que implementam a interface `AutoClosable`.
11
+
The candidate is expected to understand and analyze the use of the _try-with-resources_ statement, including classes that implement the `AutoClosable` interface.
14
12
15
-
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.
13
+
Before proceeding, based on the following example, understand the execution of the `main` method and what is presented on the console after its execution.
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.
21
+
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.
. 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`.
46
+
. 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`.
49
47
50
-
. O método `close` pode lançar uma exceção sendo capturada pelo `catch`, caso exista.
48
+
. The `close` method may throw an exception being caught by `catch`, if any.
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.
65
+
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.
68
66
69
-
. Os recursos declarados na instrução _try-with-resources_ são fechados na ordem inversa da declaração.
67
+
. Resources declared in the _try-with-resources_ statement are closed in the reverse order of the declaration.
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`.
83
+
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`.
86
84
87
-
. Os recursos declarados no _try-with-resources_ só estão disponível dentro do bloco `try`.
85
+
. Resources declared in _try-with-resources_ are only available within the `try` block.
. 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`.
101
+
. 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`.
. 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:
109
+
. 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:
112
110
+
113
-
.Antes do Java 7
111
+
.Before Java 7
114
112
[source,java]
115
113
----
116
114
public interface Closeable {
117
115
public void close() throws IOException;
118
116
}
119
117
----
120
118
+
121
-
.A partir do Java 7
119
+
.From Java 7
122
120
[source,java]
123
121
----
124
122
public interface Closeable extends AutoCloseable {
125
123
public void close() throws IOException;
126
124
}
127
125
----
128
126
129
-
. 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.
127
+
. 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.
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.
144
+
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.
147
145
148
-
. E por fim, é necessário lembrar que a instrução `try` "comum" ainda precisa obrigatoriamente de um `catch` ou `finally`.
146
+
. And lastly, it should be remembered that the _"default"_ `try` statement still necessarily needs a `catch` or `finally`.
0 commit comments