Thomas Feiner
try / catch / finally
try {
body
} catch (exception-classname variable-name) {
handler
} finally {
finally code
}
The code inside a finally block will always be executed, even if an exception is thrown within the try or catch block. When the code has a return statement within try or catch block, the code inside the finally block will get executed before returning from the method.
public class TestMyTest {
@Test
public void finallyTest() {
int value = finallyMethod();
assertEquals(??, value);
}
private int finallyMethod() {
try {
return 0;
} finally {
return 1;
}
}
}
InputStream in = getSystemResourceAsStream("test.txt" );
try (Scanner res = new Scanner( in )) {
System.out.println(res.nextLine());
}
instead of
InputStream in = getSystemResourceAsStream("test.txt" );
final Scanner res = new Scanner( file );
try {
System.out.println(res.nextLine());
} finally {
res.close();
}
If close() throws a checked exception, you have to handle it.
must be caught or declared thrown and extend java.lang.Exception
do not have to be caught or declared thrown and extend java.lang.RuntimeException
Caused by clients of a system, e.g. web client sends invalid web service request.
External or internal service does not work properly, e.g. DB is down.
Malfunction of the system, not detected by tests, dicovered during runtime. The error needs to be investigated and the application fixed and redeployed.
Serious and unrecoverable problems with the JVM. The application has to shut down immediately.
java.lang.Error, subclass of java.lang.Throwable
NEVER catch Error or Throwable!
catch (final NoSuchMethodException e) {
LOG.error("error", e);
throw e;
}
catch (final NoSuchMethodException e) {
LOG.error("error", e);
throw new MyAwesomeException(e);
}
try {
foo();
} catch (final Exception e) {
//something happened
return null; // I have seen something with "return 0" for DB counts :)
}
public void foo() throws Exception
try {
foo();
} catch (final Exception e) { //also catches checked exceptions!
LOG.error("foo failed", e);
}
try {
foo();
} catch (final Throwable t) { //also catches checked exceptions!
//wait ... what?
}
public void foo throws MyException, AnotherException, SomeOtherException, YetAnotherException { ... }
catch (NoSuchMethodException e) {
throw new MyServiceException("something went wrong" + e.getMessage); //stacktrace is lost!
}
catch (NoSuchMethodException e) {
LOG.error("something happened", e);
return null;
}
catch (MyException e) {
if (e.getCause() instanceof FooException) {
...
}
}
public String foo() {
// Not supported in this implementation.
return null;
}
http://stackoverflow.com/questions/613954/the-case-against-checked-exceptions
http://mikehadlow.blogspot.co.at/2009/08/first-rule-of-exception-handling-do-not.html
http://blogs.atlassian.com/2011/05/exceptions_are_bad/
http://tapestryjava.blogspot.in/2011/05/tragedy-of-checked-exceptions.html