/trasteando/

Playing around

Throw Defect - by Nat Pryce @ Mistaeks I Hav Made

I’ve just read this post about an interesting way to make explicit programmer errors: Throw Defect

This can be particularly useful to catch errors that are not expected to happen. Here’s an example from the original post:

1
2
3
4
5
6
7
Template template;
try {
    template = new Template(getClass().getResource("data-that-is-compiled-into-the-app.xml"));
}
catch (IOException e) {
    // should never happen
}

The ‘should never happen’ comment block can be replaced - thus making the error explicit - in the following way:

1
2
3
4
5
6
7
Template template;
try {
    template = new Template(getClass().getResource("data-that-is-compiled-into-the-app.xml"));
}
catch (IOException e) {
    throw new Defect("could not load template", e);
}