Java Try Catch Decorator - exception

I have a class with many functions
public class Test {
public void a() {
try {
doSomething1();
} catch (AException e) {
throw new BException(e.getMessage(), e.getCause());
}
}
public void b() {
try {
doSomething2();
} catch (AException e) {
throw new BException(e.getMessage(), e.getCause());
}
}
}
In each method, an exception of certain type is caught and converted to another exception and thrown.
I want to remove duplication.

You may remove duplication using lambda:
The CallableEx takes any exception, in case you are working with checked exception. You would not need it if AException was an unchecked exception. Callable interface won't help you much because it throws an Exception and not your AException: you would have to check for instance and so on.
You could probably write the body instead of this::doSomething1, but I advise against it: this makes the code clearer and it separates concerns.
You could probably also use an annotation processor to do the same job and to rewrite the method in order to wrap your AException into a BException. You would not have duplication in your Java code, but your bytecode certainly will.
Here the example with lambda:
public class Test {
#FunctionalInterface
interface CallableEx<T, E extends Exception> {
T run() throws E;
}
private <T> void handleException(CallableEx<T, AException> forrestGump) {
try {
return forrestGump.run();
} catch (AException e) {
throw new BException(e.getMessage(), e.getCause());
}
}
public String a() {
return handleException(this::doSomething1);
}
public int b(int a, int b) {
return handleException(() -> this.doSomething2(a, b));
}
public <T extends Foobar> void c(T my) {
handleException(() -> this.doSomething3(my));
}
private String doSomething1() {return "A";}
private int doSomething2(int a, int b) {return a + b;}
private <T extends Foobar> void doSomething3(T my) {my.foo();}
}

Related

how can use exception handling when we are calling a function in java

This is my code i want to call a method with another parameter with use of exception handling i want to sorround with try and catch my calling function. That Have a error of internal local variable is not assigned so i want to sorround it by try catch
how can i sorround a method calling with parameter
public void nik() {
System.out.println("nik or me ghar ja rhe he");
}
public int nik(int time) throws MyMagicExcep {
int a throw ;
System.out.println("nik or me "+a+time+" bje ghar jayege");
return 0;
}
public static void main(String[] args) {
first obj = new first();
// System.out.println();
obj.nik();
try{
System.out.println("harsh bhaiya mja nhi aaya");
obj.nik(1);}
catch(MyMagicExcep e) {
System.out.println("harsh bhaiya mja nhi aaya");
}
obj.nik();
}
}```

junit for multi threaded class with mockito

Please, help me write a JUnit test for this code using Mockito.
class A{
private BlockingQueue<Runnable> jobQueue;
public void methodA(List<String> messages) {
try {
jobQueue.put(() -> methodB(message));
} catch(InterruptedException e) {}
}
private void methodB(Message message) {
//other logic
}
}
Your example lacks context as to what it is methodB is doing... Without knowing what the functionality is that you want to verify, just verifying that methodB gets called wouldn't be a particularly useful test, nor is mocking the BlockingQueue. I'm going to go out on a limb and assume that methodB interacts with another object, and it's this interaction that you really want to verify, if that's the case my code and test would look something like:
class A {
private BlockingQueue<Runnable> jobQueue;
private B b;
public void methodA(Message message) {
try {
jobQueue.put(() -> methodB(message));
} catch (InterruptedException e) {
}
}
private void methodB(Message message) {
b.sendMethod(message);
}
}
class B {
public void sendMethod(Message message) {
// other logic
}
}
And my test would potentially look something like:
class Atest {
private A testSubject;
#Mock
private B b;
#Test
public void testASendsMessage() {
Message message = new Message("HELLO WORLD");
testSubject.methodA(message);
verify(b, timeout(100)).sendMethod(message);
}
#Before
public void setup() throws Exception {
testSubject = new A();
}
}
In general you want to avoid needing to verifying bits with multiple threads in a unit test, save tests with multiple running threads mainly for integration tests but where it is necessary look at Mockito.timeout(), see example above for how to use. Hopefully this helps?

rxjava reactor, Utility to propagate exception

I'm trying to write an utility which automatically propagate checked exception in a reactiv way without writing boiler plate code with static block inside my operators:
public class ReactRethrow {
public static <T, R> Function<T, R> rethrow(Function<T, R> catchedFunc) {
return t -> {
try {
return catchedFunc.apply(t);
} catch (Exception e) {
throw Exceptions.propagate(e);
}
};
}
}
but it stil complaining about IOException here:
Flux.fromArray(resources).map(ReactRethrow.rethrow(resource -> Paths.get(resource.getURI())))
any idea?
Well for a reason I do not clearly understand You have to take as parameter a function which throw exceptions and so declare a specific functionalInterface:
public class ReactRethrow {
public static <T, R> Function<T, R> rethrow(FunctionWithCheckeException<T, R> catchedFunc) {
return t -> {
try {
return catchedFunc.call(t);
} catch (Exception e) {
throw Exceptions.propagate(e);
}
};
}
#FunctionalInterface
public interface FunctionWithCheckeException<T, R> {
R call(T t) throws Exception;
}
}
from here https://leoniedermeier.github.io/docs/java/java8/streams_with_checked_exceptions.html

Catch and Re-throw Exceptions from JUnit Tests

I am looking for a way to catch all exceptions thrown by JUnit tests then re-throw them; to add more detail to the error message about the test state when the exception occurred.
JUnit catches errors thrown in org.junit.runners.ParentRunner
protected final void runLeaf(Statement statement, Description description,
RunNotifier notifier) {
EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);
eachNotifier.fireTestStarted();
try {
statement.evaluate();
} catch (AssumptionViolatedException e) {
eachNotifier.addFailedAssumption(e);
} catch (Throwable e) {
eachNotifier.addFailure(e);
} finally {
eachNotifier.fireTestFinished();
}
}
This method is unfortunately is final so it cannot be overridden. Also as exceptions are being caught something like Thread.UncaughtExceptionHandler will not help. The only other solution I can think of is try/catch block around each test but that solution is not very maintainable. Could anyone point me to a better solution?
You could create a TestRule for this.
public class BetterException implements TestRule {
public Statement apply(final Statement base, Description description) {
return new Statement() {
public void evaluate() {
try {
base.evaluate();
} catch(Throwable t) {
throw new YourException("more info", t);
}
}
};
}
}
public class YourTest {
#Rule
public final TestRule betterException = new BetterException();
#Test
public void test() {
throw new RuntimeException();
}
}

rxjava - How to handle merge exceptions without terminating the whole process

I have created two observables.
One of them throws an exception.
obs1 = Observable.from(new Integer[]{1, 2, 3, 4, 5, 6});
obs2 = Observable.create(new Observable.OnSubscribe<Integer>() {
#Override public void call(Subscriber<? super Integer> subscriber) {
boolean b = getObj().equals(""); // this throws an exception
System.out.println("1");
}
});
Now I invoke them using
Observable.merge(obs2, obs1)
.subscribe(new Observer<Integer>() {
#Override public void onCompleted() {
System.out.println("onCompleted");
}
#Override public void onError(Throwable throwable) {
System.out.println("onError");
}
#Override public void onNext(Integer integer) {
System.out.println("onNext - " + integer);
}
});
Now, I dont want my process to halt completely when an exception occurs -
I want to handle it and I want obs1 to continue its work.
I have tried to write it using onErrorResumeNext(), onExceptionResumeNext(), doOnError()
but nothing helped - obs1 did not run.
How can I handle the exception without stopping the other observable from being processed?
Sounds like you need mergeDelayError.
The problem is in your subscriber which is broken. You should catch your exception and call onError. Otherwise, you broke the rx contract.
example :
Observable<Integer> obs1 = Observable.from(Arrays.asList(1, 2, 3, 4, 5, 6));
Observable<Integer> obs2 = Observable.create((Subscriber<? super Integer> subscriber) -> {
subscriber.onError(new NullPointerException());
});
Observable.merge(obs2.onErrorResumeNext((e) -> Observable.empty()), obs1)
.subscribe(new Observer<Integer>() {
#Override public void onCompleted() {
System.out.println("onCompleted");
}
#Override public void onError(Throwable throwable) {
System.out.println("onError");
}
#Override public void onNext(Integer integer) {
System.out.println("onNext - " + integer);
}
});
so if you replace your obs2 code with this, it should work like you expected :
obs2 = Observable.create(new Observable.OnSubscribe<Integer>() {
#Override public void call(Subscriber<? super Integer> subscriber) {
try {
boolean b = getObj().equals(""); // this throws an exception
System.out.println("1");
} catch(Exception ex) {
subscriber.onError(ex);
}
}
});