Checked exception specification and strategy pattern - java

I am a c++ developer and I am pretty new with the checked and unchecked exception in java. The exception specifications in c++ are simply not good and that's why nobody is using it. I like the checked exception and I have a question, let's have this interface:
public interface Warehouse {
MyStuff fetch(int id);
}
The warehouse can be implemented in different way: file, database or in memory (mock object for test).
Now, if I want to implement using a file, I cannot try to open the file in the method otherwise my signature will change and my class will not implement the interface anymore. Also if I had another class with another checked exception all the other existing implementation will be affected.
I can see two solutions:
Catch the checked exception and throw another custom runtime exception. I don’t think this is a good solution, why the user should catch a runtime exception saying that a file is missing when there is already a standard and checked way to do that.
Do the entire job in the constructor of the implementation class and leave the fetch function unable to throw. I like this way, the object both exists and is valid or it doesn’t exist. The only drawback on this approach is that we cannot implement a lazy evaluation; we need to read and parse the file in the constructor even though nobody will use the object. This is not efficient.
Am I missing something? Is there a better way to avoid this problem?

Your first solution is the right one. Change your interface to :
public interface Warehouse {
MyStuff fetch(int id) throws FetchFailureException;
}
And make every subclass wrap its IO, JDBC or whatever exception inside a FetchFailureException. This FetchFailureException exception should be runtime if unrecoverable, and checked if recoverable.

Personally, I would have Warehouse list all the exceptions it can throw (including unchecked ones in the javadoc)
If you have an exception which is not listed, you need to handle it or wrap it. (Whether its checked or not)
You have to make your mind up whether you want Warehouse to throw an checked exception or not. You can't have it both ways. (Actually you can but its not a good idea as you can blindly throw a checked exception without the compiler knowing)

The Best practice is to specify the exceptions which the method will be throwing in the interface.
Suppose you have a custom Exception class :
class MyException extends Exception { public MyException
(String message) { super(message); } public
MyException (String message, Exception cause) { super(message,
cause); }
}
Handle all your exceptions in MyException class,
Now you can specify the exception which your method should throw in the interface
public Interface Warehouse
{
public MyStuff fetch() throws MyException;
}

I would suggest you to include in the Warehouse class all the exceptions and then working with subinterfaces in order to work with non checked exceptions, like this:
public interface Warehouse {
MyStuff fetch(int id) throws FileNotFoundException;;
}
public interface FileWarehouse extends Warehouse {
#Override
MyStuff fetch(int id) throws FileNotFoundException;
}
public interface OtherWarehouse extends Warehouse {
#Override
MyStuff fetch(int id);
}

Related

Throwing custom exceptions in a functional interface

I am writing a program that consumes some data from a RabbitMQ API, via the java.function.Consumer functional interface. In my subclass that implements this interface, I have 3 potential exceptions:
public interface MyMessageHandler extends Consumer<MyMessage> {}
public class SpecificMessageHandler implements MyMessageHandler {
#Override
public void accept(IncomingMessage incomingMessage) {
if(incomingMessage.getTime() < 1000) {
throw new InvalidTimeException("message"); //Custom exception extends RuntimeException
}
if(incomingMessageAlreadyExists) {
throw new DuplicateMessageException("message"); //Custom exception extends RuntimeException
}
try {
ObjectMapper.reader.readValue(incomingMessage.getJson()) // Throws IOEXception
} catch(IOException e) {
throw new CustomIOException("message"); //Custom exceptin extends RuntimeException
}
// If all is well, carry on with rest of function
}
}
I am having to take this route because you can't seem to throw regular exceptions in a functional interface, it has to be a runtime exception.
I am throwing the exceptions at this level of the stack, as I want to implement the actual handling behaviour higher up the stack, due to the fact I will have many message handlers that will be handled in the same way, therefore it's easier to implement that handling behaviour once higher up, rather than in every single handler class.
This functionally works, however feels like bad design. Is there a more elegant way to implement this? Note, I can't switch from a functional interface to something else, as i'm working with legacy code (not ideal, but that's how the world is some times!)
I am having to take this route because you can't seem to throw regular
exceptions in a functional interface, it has to be a runtime
exception.
This is incorrect. You can't throw checked exceptions in a java.function.Consumer specifically, because its signature
void accept(T t);
doesn't declare any.
The following functional interface is perfectly acceptable, and can throw certain checked exceptions.
public interface MyMessageHandler {
void accept(IncomingMessage incomingMessage) throws IOException;
}
MyMessageHandler handler = (msg) -> {
throw new IOException(); // Valid
};
If you wanted something more generic, you could declare something like
public interface ThrowableConsumer<T> {
void accept(T t) throws Exception;
}
interface MyMessageHandler extends ThrowableConsumer<MyMessage> {}
I am throwing the exceptions at this level of the stack, as I want to
implement the actual handling behaviour higher up the stack
You could use Lombok's #SneakyThrows to effectively convert a checked exception into an unchecked one. A hack, but it works.
class SpecificMessageHandler implements MyMessageHandler {
#Override
#SneakyThrows
public void accept(IncomingMessage incomingMessage) {
// Doesn't matter that it's checked and j.f.Consumer doesn't declare it
throw new IOException();
}
}
However I highly doubt that your employer will allow you to do hacks like this if you're not permitted to change an interface.
This functionally works, however feels like bad design
Why? There's a huge class of people who believe that checked exceptions were a mistake to begin with. There's nothing wrong with runtime exceptions.
Note, I can't switch from a functional interface to something else, as
i'm working with legacy code
People throw this word around a lot. Java 8 came out 8 years ago. Your code can't be that old. Usually when people say "I can't change X", what they mean is that they don't feel comfortable changing it, for whatever reason. If you're living in fear of your software, find a way to change that.

How to centralize exception handling in multiple methods of an API

This is a plain Java 8+ question, no frameworks used.
We are producing an API for a higher layer which deals with the presentation layer among other activities. We have and interface agreed with the invoker, so they are happy to receive some particular exceptions we throw.
At the same time, we are also using other APIs under the same agreement, so we can do stuff by ourselves and throw exceptions or we can invoke other APIs which throw the agreed exceptions.
Currently, we do nothing with the exceptions thrown by the APIs we are invoking.
Thing is, we are the best positioned in this infrastructure to deal with intermediate activities while exceptions are thrown, so we need to capture both, our exceptions and the exceptions provided by those we are invoking; basically reporting the issue, raising system controls, etc, and then re-throw the original exception so the top layer keeps as it is now.
We have around 300 methods in the entry point class of our API:
public void method1 (arguments for method 1) {
...
}
...
public void method300 (arguments for method 300) {
...
}
I clearly understand that I can create a method to centralise the actions to be taken in the exception management, something like:
public void myExceptionHandler (Exception e) {
if (e instanceOf X) {
} else if ...
...
throw particularExceptionAccordingTheCase
}
But I'd also avoid modifying those 300 methods.
Any idea how to inject a try-catch in those 300 methods to send the Exception to myExceptionHandler without really adding a try-catch in each of them?
Any comments and ideas are much appreciated!
----------- After mprev0 suggestion -------------------------------
I tried this approach. It really catches the exception and so on, but I can't re-trow an Exception: I'm forced to catch it, but this goes against the requirement of re-sending the exception back to the top layer.
While I can throw an Error, I got a compiler error at line throw new FileNotFoundException();
public class myExceptionHandler implements Thread.UncaughtExceptionHandler {
#Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("gotcha!");
if (e instanceof java.lang.Error) {
System.out.println("AAT-CORE: Fatal Error");
throw new java.lang.Error(e.getCause());
} else if (e instanceof java.lang.Exception) {
System.out.println("AAT-CORE: Exception Error");
throw new FileNotFoundException();
}
}
}
Any ideas?
------------ After some more digging, fixed with a decorator pattern -------
Previous class implementation does not work, as I can't change the signature of the method and I need to re-throw the java.lang.Exception.
Using a decorator and handling the interface there makes the trick.
As a summary:
Top layer class:
public class TopLayer {
public static void main (String[] args) {
MiddleLayer m = new MiddleLayer();
m.method1();
}
}
Bottom layer class contains specific APIs and some implementation, the only interesting thing is that it contains java.lang.Exceptions uncontrolled, expecting the top layer to do this job. But, we are working in the middle and we will do this job:
public class MiddleLayer extends BottomLayer {
public MiddleLayer () {
final UncaughtExceptionHandler subclass = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable ex) {
System.out.println("gotcha2!");
// carry on with prior flow
subclass.uncaughtException(thread, ex);
}
});
}
}
In this way, I can get the system.out and the java.lang.Exception is propagated to the Top Layer.
Decorator inspiration came from here: Rethrow UncaughtExceptionHandler Exception after Logging It
Additional comments are welcome!
You can solve this by implementing the java.lang.Thread.UncaughtExceptionHandler interface:
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
#Overrides
public void uncaughtException(Thread t, Throwable e) {
if (e instanceOf X) {
} else if ...
...
throw particularExceptionAccordingTheCase
}
}
Then you associate it to all threads as follows:
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler())
This will configure the exception handler to handle all uncaught exceptions in all threads of your application.
Note that this will only work for exceptions that aren't yet explicitly handled somewhere in your code and if there is no other handler configured for some particular thread (the uncaught exception handler can also be set for some specific thread).
EDIT: As discovered by #JBC, the above approach will not work for checked exceptions since we are forced to catch them explicitly in our uncaughtException method (note that we cannot add a throws clause to an overridden method). While it will work without problems if we only want to re-throw subtypes of RuntimeException and Error, there is a little adaptation needed if we want to make it work - you can find it explained in #JBC's question.
As you can see in the question updates, the final solution is a combination of two different approaches, in one side, having the mprev0 approach of implementing the java.lang.Thread.UncaughtExceptionHandler and, on top of this, adding a Decoration pattern to be able to re-throw a run-time exception.
There were no additional approaches so far, so I'm closing the question and bring this as the most complete response.
More information about UncaughtExceptionHandler can be found in the Java documentation, but as always, is short on examples, and here:
Advanced exception handling
Thread.UncaughtExceptionHandler Example
More information on Decorator pattern usage, can be found here:
Decorator Design Pattern in Java
Design Patterns - Decorator Pattern
And how to use to manipulate exceptions here:
Rethrow UncaughtExceptionHandler Exception after Logging It
You could also create a proxy API on top of your current API, have an invocation handler method in the proxy and put this method in a try catch block.
https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html
https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html

SonarQube error: Refactor this method to throw at most one checked exception

I am using SonarQube and it shows the following error:
Public methods should throw at most one checked exception.
// Noncompliant
public void delete() throws IOException, SQLException { /* ... */ }
// Compliant
public void delete() throws SomeApplicationLevelException { /* ... */ }
Does this means, SomeApplicationLevelException is a parent class and IOException and SQALException are derived from it? And we should throw the parent class exception? Thereby adhering to method throwing only 1 checked exception?
Because I have 2 exceptions that i have defined say for example Exception1 and Exception2 that extend Exception. And my method say, sampleMethod() throws them i.e,
public void sampleMethod() throws Exception1, Exception2 {
}
And the error is shown here. So should I have one class as parent (say MainException) and derive Exception1 and Exception2 from it and throw parent exception class? Like below:
public void sampleMethod() throws MainException {
}
Is the above solution proper?
If you have a method in your application that is declared as throws SQLException, IOException, you are probably leaking internal implementation details to your method's users. Specifically, you're saying:
Your method is implemented using JDBC and file I/O. Your users don't care how your method is implemented; they only care about what your method does.
Your method, including any future version of it, will never throw any other checked exception. If in future you change your method so that it might throw another checked exception, it will break backwards compatibility.
The advice is to create your own application-specific class (derived from Exception), and only throw that in your method. You can, if you like, wrap the SQLException or the IOException (or any other exception) inside your application-specific exception as the cause.
Note, however, that there is a school of thought that says Java checked exceptions are a bad idea (and one of the reasons C#, and more modern languages such as Kotlin, don't have checked exceptions).
UPDATE: the above answer related to the first version of the question (edit #1). The question was subsequently updated to point out that the two thrown exceptions were application-defined ones, so therefore much of the above rationale no longer applies. The answer to the updated question is explained in this post.
IOexception and sqlexception both are checked exception s,totally different from each other , now if we extend both from one exception and throw the parent exception , which is not a mandatory in java, it will be kind of misguiding the user of the api.
However, if you want to do it in ur app to avoid sonarqube error , you can catch all your specific exceptions and throw a custom exception wrapping the original exception information in exception message.
for example
try{
///piece of code that throws IOException and SQLException
}catch(IOException | SQLException ex){
throw new DataException(ex,"Any customized message you want");
}
This DataException will then will be included in the throws clause of method signature having this try catch.
DataException extends Exception class and by passing ex in the contructor you are wrapping the original exception in custom exception with your original exception info preserved.

Unhandled exception type Exception

This is a simplified class that describes my problem:
public class Main {
enum Test{
First(method()){ // Unhandled exception type Exception
// ...
};
Test(Object obj){
//...
}
}
static Object method() throws Exception{
// ...
if (someCondition){
throw new Exception();
}
}
}
Above someCondition depends on device and some situations and I can not decide in about it now, also as you can see, I do not want to catch Exception in method.
Yes. It is a compilation error.
No. There is no special syntax to deal with this.
I do not want to catch Exception in method.
Unfortunately if you throw a checked exception, it has to be caught further up the call stack. That is a fundamental design principal for the Java language, and one that the compiler enforces strictly.
In this, case there is no way to catch the checked exception. Hence, if you are going to call a method in enum constant parameter (as per your code), the method cannot throw a checked exception1.
Here is a possible workaround, though this is probably a bad idea:
public class Main {
enum Test{
First(methodCatchingException()){
// ...
};
Test(Object obj){
//...
}
}
static Object method() throws Exception{
// ...
if (someCondition){
throw new Exception();
}
}
static Object methodCatchingException() {
try {
return method();
} catch (Exception ex) {
throw new SomeRuntimeException("the sky is falling!", ex);
}
}
}
Another way to look at this problem is to ask yourself what should happen with the exception if the compiler let you write that ... and an exception was thrown? Where would it go?
You can't catch it ... because the enum initialization is like a static initialization.
If the Java runtime completely ignored the thrown exception, that would be really bad.
If the Java runtime crashed, then the model of checked exceptions is broken.
So, what this is saying to me is that the Java language design is right, the Java compiler is right ... and the real problem here is in your application design:
You should not be propagating a checked exception here. If an exception occurs in this context it is categorically NOT a recoverable error.
Maybe it is inadvisable to use an enum for this ... because of the potential for non-recoverable initialization errors.
(Note that if this method call terminates due to an unchecked exception, it will turn it into an ExceptionInInitializerError. In addition, the JVM will mark the enum class as uninitializable, and will throw an NoClassDefFoundError if your application attempts to use it; e.g. via Class.forName(...).)
I assume that Exception is used here for illustration purposes. It is a bad thing to declare methods as throws Exception or to throw new Exception(...)
1 - I had a look at the JLS for something to back this up. As far as I can tell, the spec does not mention this situation. I'd have expected to see it listed in JLS 11.2.3. However, it is clear that a compiler cannot allow a checked exception to propagate at that point as it would "break" the model of how checked exceptions work.
I don't think you want to be throwing a checked exception here (which is what Exception is). The reason: you're invoking the call of method inside of the constructor of Test. There's really not a clean way to deal with it.
While the obvious choice here is to switch to RuntimeException, I want you to reconsider throwing the exception in the first place. Since your enum will only ever have First declared in it, does it really make sense for it to throw an exception when it's being instantiated? Personally, I don't think it does; whatever dangerous operation it's doing should be deferred until you want to invoke it, and then would you want to throw your exception.

Cannot inherit from Exception

Im' trying to write a class BrokenObjectException class derivated from Exception.
But in Eclipse I get this error:
The serializable class BrokenObjectException does not declare a static final serialVersionUID field of type long
public class BrokenObjectException extends Exception
{
BrokenObject(String message)
{
;
}
}
I have not understood why it asks me to declare a field.
Shouldn't interface just force to declare some methods?
Anyway I want to have this class because I want to catch it n a different way from how I catch all exceptions, from I example I have a block:
try
{
if(...)
throw new Exception("wrong");
if(...)
throw new BrokenObjectException("wrong");
}
catch(BrokenObjectException e)
{
// do something (action1)
throw e;
}
catch(Exception e)
{
// so something (action2)
throw e;
}
So in the first catch block I have written "do something".
This because depending on the type of exception thrown I want to do different actions.
So since BrokenObjectException is derivated from Exception it shall be catched two times.
But if a BrokenObjectException is thrown, I want to do action1 and action2, if just a normal Exception is thrown I want just to do action2.Is that possible?
And how to fix the error I'm getting?
That's not an error but rather just a warning. Simply use the #SuppressWarnings("serial") annotation just above the class declaration:
#SuppressWarnings("serial")
public class BrokenObjectException extends Exception
{
BrokenObject(String message)
{
;
}
}
What is happening is you are extending a class that implements the Serializable interface and so the compiler will warn you if you do not fully comply with its contract. To get around this (since I doubt that you'll want to serialize objects of this class), simply use the annotation above.
I believe that you can just highlight over the error text that eclipse gives you and then tell it to generate the serial version UUID. After that, it should work just how you want it to.
Also you can use the
#SuppressWarnings("serial")
if you want to just ignore it. However, I would recommend going ahead and generating it. For more info on why check out this stack overflow post.
What is a serialVersionUID and why should I use it?
Are you aware why is that serialVersionUID field needed? Is that what you are asking for? if so please look at the following link

Categories