jueves, 1 de julio de 2010

Wrap your Exception as a RuntimeException when it is not of your method's business

A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.


package exceptions;

public class RuntimeExceptionTest {

public class TestException extends Exception {

}

public static void main(String[] args) {
RuntimeExceptionTest test = new RuntimeExceptionTest();
try {
test.throwWrappedTestExceptionAsRuntimeException();
} catch (Exception e) {
System.out.println("exception catched:\n");
e.printStackTrace();
}
}

private void throwTestException() throws TestException {
throw new TestException();
}


public void throwWrappedTestExceptionAsRuntimeException() {
try {
throwTestException();
} catch (TestException e) {
throw new RuntimeException(e);
}
}
}

No hay comentarios: