mahmood
mahmood

Reputation: 24705

IOException handling in multiple methods

Consider the following code

public class foo {
  public static void main(String[] args) {
    MyClass mc = new MyClass();
    mc.read();
  }
}

and

public class MyClass {
  private BufferedWriter verb;
  private String vFile;
  MyClass()
  {
    try {
      verb = new BufferedWriter(new FileWriter(vFile));
    } catch(IOException e) {
      System.out.println("Internal error1");
      System.out.println(e.getMessage());
    }
  }
  public void read()
  {
    // read a file and create an array
    verb.write("Array created");    // ERROR
  }
}

As you can see the write is not placed in a try..catch block. I can write a catch for that, but MyClass has many methods and verb.write is used heavily. I also can write public void read() throws IOException to throw the exception to the the caller, main(). Still I have to put mc.read() in a try..catch block. Since MyClass has numerous methods, then I have to put all of them in a catch block in the main().

So, is there a better way to handle that? Is it possible to redirect all exceptions related to verb to the constructor, MyClass() where a try..catch is defined?

Upvotes: 1

Views: 154

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

One approach is to make your own "safe" wrapper around BufferedWriter (for that matter, any kind of Writer) and handle I/O errors there:

class SafeWriter {
    private final Writer writer;
    public SafeWriter(Writer writer) {
        this.writer = writer;
    }
    public void write(int n) {
        try {
            writer.write(n);
        } catch (IOException e) {
            handleException(e);
        }
    }
    public void write(String s) {
        try {
            writer.write(s);
        } catch (IOException e) {
            handleException(e);
        }
    }
    ... // Provide wrappers for other methods here
    private void handleException(IOException e) {
        ...
    }
}

Now you can use write methods on your new class to handle exceptions in a uniform way inside the class:

private SafeWriter verb;
...
verb = new SafeWriter(new BufferedWriter(new FileWriter(vFile)));

Upvotes: 1

Related Questions