2

throws IOException 用于来自文件的输入。

4

3 回答 3

4

像这样的东西:

import java.awt.event.*;
import java.io.*;
class Foo implements MouseListener {
    void io() throws IOException {
        File file = new File("foo");
        FileReader fileReader = new FileReader(file);
        fileReader.read();
        // ...
    }
    @Override public void mouseClicked(MouseEvent arg0) {
        try {
            io();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Override public void mouseEntered(MouseEvent arg0) {}
    @Override public void mouseExited(MouseEvent arg0) {}
    @Override public void mousePressed(MouseEvent arg0) {}
    @Override public void mouseReleased(MouseEvent arg0) {}
}
于 2011-11-24T00:04:24.100 回答
2

类不会抛出异常,方法会。

public class Foo implements MouseListener {
    public void throwingUp() throws IOException {
        // ... Code that could throw IOE
    }
    // ... MouseListener impl
}
于 2011-11-23T23:57:38.603 回答
0

类不会抛出 IOExceptions,方法会。您的类可以实现 MouseListener,但那些方法(mouseClicked、mousePressed 等)不能抛出 IOExceptions。您必须将它们包装在 RuntimeException (或子类)中。例如

   @Override
   public void mouseEntered(MouseEvent e) {
      try {
         methodThatMightThrowAnIOException();
      }
      catch (IOException ioe)
      {
         throw new RuntimeException(ioe);
      }
   }

其他方法,如methodThatMightThrowAnIOException(),可以抛出 IOExceptions。

于 2011-11-24T00:04:35.543 回答