try { libApp.addBook(book1); } catch (OperationNotAllowedException e) { // Error handling code, e.g. telling the user that he is not logged in as adminstrator }
In JUnit test code or Cucumber step definitions, you never want to catch an exception unless you are testing for the fact that an exception is thrown. The reason is, that you want to propagate any erronous situation to the runner of the test case to show to the user. If the exception is a checked exception, you can just add them to the throws clause of the test method.
The Java compiler complains when a checked exception is not either handled or added to the throws clause of the method. The default try-catch block generated by Eclipse, just prints the stack trace to the console or log file and continous otherwise. For testing purposes, this is bad, as you have to look at the console output to see if something is wrong. However, one wants that the JUnit test runner shows the problem. Also, in a development and production environment, this is bad. If the exception is just recorded in the log file, people are likely to oversee the problem instead of looking at the root cause of that error to prevent it, or to deal with it in an appropriate manner. Therefore, my recommendation is, that one
try { /* some code */ } catch (MyException e) { throws new Error(e); }In this case, the compiler does not complain anymore, but the exceptional situation is immediatly propagated to the user or the developer and can be fixed. This is an example of the principle "fail fast" used in Lean production.