I’m coding like it’s 2000, meaning in Java. I thought I’d never see anything new regarding writing a test that expects to catch a specific exception. I saw something new, and I wonder who else has independently discovered it.

public void ioFailure() throws Exception {
    final IOException ioFailure = new IOException("Simulating a failure writing to the file.");
    try {
        new WriteTextToFileActionImpl() {
            protected FileWriter fileWriterOn(File path) throws IOException {
                return new FileWriter(path) {
                    public void write(String str, int off, int len) throws IOException {
                        throw ioFailure;
        }.writeTextToFile("::text::", new File("anyWritableFile.txt"));
        fail("How did you survive the I/O failure?!");
    } catch (IOException success) {
        if (success != ioFailure)
            throw success;

Please add your comments at

(If you can’t see the code snippet inline, then click here.)

Design credit: Shashank Mehta