Exception – 15

      在〈Exception – 15〉中尚無留言

Q001

NO.24 Given:
import java.io.FileNotFoundException;
import java.io.IOException;
class Tester {
    public static void main(String[] args) {
        try {
            doA();
        } // line 1
    }
    private static void doA() throws IOException, IndexOutOfBoundsException {
        if (false) {
            throw new FileNotFoundException();
        } else {
            throw new IndexOutOfBoundsException();
        }
    }
}
What must be added in line 1 to compile this class?
A. catch(IOException e) { }
B. catch(FileNotFoundException | IndexOutOfBoundsException e) { }
C. catch(FileNotFoundException | IOException e) { }
D. catch(IndexOutOfBoundsException e) { } catch(FileNotFoundException e) { }
E. catch(FileNotFoundException e) { } catch(IndexOutOfBoundsException e) { }


Answer: A

IndexOutOfBoundsException 是 unchecked,所以不用 catch。

另外 IOException 是父類別,FileNotFoundException 是子類別,二者不可以寫在一起。

Q002

NO.48 Given:
public class Main {
    private String[] strings = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
     "abcdefghijklmnopqrstuvwxyz", "0123456789" };
    public void write(String filename) {
        // line 1
            for (String str: strings) {
                ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
                fileChannel.write(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Main test = new Main();
        test.write("file_to_path");
    }
}
You want to obtain the Filechannel object on line 1. Which code fragment will
accomplish this?
A. try (FileChannel fileChannel = Channels.newChannel(new
FileOutputStream(filename));) {
B. try (FileChannel fileChannel = new FileOutputStream(filename).getChannel();) {
C. try (FileChannel fileChannel = new FileOutputStream(new
FileChannel(filename));) {
D. try (FileChannel fileChannel = new FileChannel(new
FileOutputStream(filename));) {


Answer: B

FileChannel 是用來將資料寫入到檔案,正確組合方式為

FileOutputStream fos = new FileOutputStream(filename);
FileChannel fileChannel = fos.getChannel();
fileChannel.write(buffer);

🔒 底下內容僅限會員閱讀。

立即登入

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *