[OCPJP]try-with-resources敘述的用法5

Given the code fragment:

Assume that the ready method of the BufferedReader, when called on a closed BufferedReader, throws an exception, and employee.txt is accessible and contains valid text.

What is the result?

A. A compilation error occurs at line n3.
B. A compilation error occurs at line n1.
C. A compilation error occurs at line n2.
D. The code prints the content of the employee.txt file and throws an exception at line n3.

題解

br變數所參考到的BufferedReader物件為try-with-resources結構的資源,因此在離開try-with-resources結構的try區塊後,資源就會被釋放(BufferedReader物件會close)。

line n3的部份在BufferedReader物件被close之後呼叫ready方法,所以會拋出IOException。

關於作者

Magic Len

各位好,我是Magic Len,是這網站的管理員。我是台灣台中大肚山上人,畢業於台中高工資訊科和台灣科技大學資訊工程系,曾在桃機航警局服役。我熱愛自然也熱愛科學,喜歡和別人分享自己的知識與經驗。如果你有興趣認識我,可以加我的Facebook,並且請註明是從MagicLen來的。

相關文章