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

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();
}
}```

Related

JUnit Mockito: Testing a Static Method and Calling Another Stubbed Static Method Inside Not Working

class A {
public static int f1() {
return 1;
}
public static int f2() {
return A.f1();
}
}
class ATest {
#Test
void testF2() {
try (MockedStatic<A> aStatic = Mockito.mockStatic(A.class)) {
aStatic.when(A::f1).thenReturn(2);
int ret = A.f2(); // getting 0 here
assertEquals(ret, 2);
} catch(Exception e) {
}
}
}
In the testF2 I want to test static function A::f2().
And it internally calls another static function A::f1().
I did stub A::f1() to return 2 using "MockedStatic" and "when" way.
But it's not working, it's returning 0.
How to solve it?
I think you miss to specify a mock behavior:
class ATest {
#Test
void testF2() {
try (MockedStatic<A> aStatic = Mockito.mockStatic(A.class)) {
aStatic.when(A::f1).thenReturn(2);
aStatic.when(A::f2).thenReturn(A.f1()); // <- added this
int ret = A.f2(); // getting 0 here
Assertions.assertEquals(ret, 2);
} catch (Exception e) {
}
}
}
by telling the mock what to do when A.f2() is invoked, test runs fine.
Update:
Mocks do what you tell them, if you don't tell what to do when a method is invoked they do nothing, that's why you have to mock f2 too.
You want to test A, then mock it is not your friend. I normally use a Mockito.spy() to partially mock my subject under test .You want to mock f1 but test f2, I don't think spy applies here because there is no instance to spy..
I suggest you to rearrange A avoiding static methods if possible or using parameters you can mock.
When you mock a class with static methods, all static methods are mocked. If you only want to mock the behavior of only 1 method, you have to add Mockito.CALLS_REAL_METHODS argument to Mockito.mockStatic() as you can see in the following example.
#Test
void testF2() {
try (MockedStatic<A> aStatic = Mockito.mockStatic(A.class, Mockito.CALLS_REAL_METHODS)) {
aStatic.when(A::f1).thenReturn(2);
int ret = A.f2(); // getting 2 here
Assert.assertEquals(2, ret); // (expected, result)
} catch(Exception e) {
}
}
This way only the f1 method invocation is mocked but f2 invocation calls the real code.

Add more context to Exception or Error in Groovy

When I want just to add more context to any exception that has happened (including parsing errors and even out of memory) I write code as follows
try {
new JsonSlurper().parseText(response)
} catch (any) {
throw new IllegalStateException("Cannot parse response:\n$response", any)
}
This works fine, but I may end up with OutOfMemoryError being wrapped in IllegalStateException which doesn't sound right, as further there could be dedicated exception handling mechanism just for Error throwables.
Is there any way to just add more context to exception and still preserve its original type or category? I.e. when I get OOME, I want to rethrow Error, when I get some parsing exception, I want to rethrow some unchecked exception etc. And of course I don't want to do it manually for each category, as OOME is pretty unlikely and I don't want to produce special code for corner cases (while still I want to be technically correct).
You can definitely do this in groovy by using its metaprogramming features. In particular, for your case metaclasses provides everything you need. Using them you can dynamically add/attach a contextData object to the exception you want it to carry around:
private static void throwsEnhancedException() throws IOException {
try {
throwsBasicException()
} catch (IOException e) {
e.metaClass.contextData = "My context data"
throw e;
}
}
Then to retrieve this contextData in other parts of the code, just inspect the exception object like this:
private static void doSomethingWithContextData(Closure contextDataHandler) throws IOException {
try {
throwsEnhancedException();
} catch (IOException e) {
// RETRIEVE `contextData` FROM `e` OR NULL IF THE PROPERTY DO NOT EXIST
def contextData = e.hasProperty('contextData')?.getProperty(e)
// DO SOMETHING WITH `contextData`
contextDataHandler(contextData)
}
}
There I am using the argument contextDataHandler as a groovy Closure to handle contextData in a flexible manner.
The following is a full working demo of this:
import java.time.LocalDateTime
class ExceptionEnhancer {
static void main(String[] args) {
def logger = { println "${LocalDateTime.now()} - Context Data = [$it]" }
doSomethingWithContextData logger
}
private static void doSomethingWithContextData(Closure contextDataHandler) throws IOException {
try {
throwsEnhancedException();
} catch (IOException e) {
// RETRIEVE `contextData` FROM `e` OR NULL IF THE PROPERTY DO NOT EXIST
def contextData = e.hasProperty('contextData')?.getProperty(e)
// DO SOMETHING WITH `contextData`
contextDataHandler(contextData)
}
}
private static void throwsEnhancedException() throws IOException {
try {
throwsBasicException()
} catch (IOException e) {
e.metaClass.contextData = "My context data"
throw e;
}
}
public static void throwsBasicException() throws IOException {
throw new IOException();
}
}
Complete code on GitHub
Hope this helps.

Java Try Catch Decorator

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();}
}

Handling Exception in Function

I stumbled over this problem. Lets say i have an Func1 which parses some json string and returns the ServerState (Enum). For some reason the state cant be unknown by the Client or the JSON is bad for some reason.
How do i propagate the Exception from call Method ?
public static class ParseProgressFunction implements Func1<String, Observable<ServerState>> {
#Override
public Observable<ServerState> call(String progress) {
try {
final ServerState serverState = ServerParser.parseProgress(progress);
} catch (JSONException e) {
e.printStackTrace();
} catch (UnknownServerStateException e) {
e.printStackTrace();
}
}
}
This is the Idea i like to implement this:
#Override
public void onReceiveServerState(final Observable<String> state) {
state.flatMap(new ParseProgressFunction());
There must be some best practice, right ?
Happy Easter
As your function return an Observable, you can return a new error Observable with your exception.
return Observable.error(you exception);

How to re-throw exception in AspectJ around advise

I have some methods which throws some exception, and I want to use AspectJ around advise to calculate the execution time and if some exception is thrown and to log into error log and continue the flow by re-throwing the exception.
I tried to achieve this by following but eclipse says "Unhandled Exception type".
Code-against whom AspectJ is to used :-
public interface Iface {
public void reload() throws TException;
public TUser getUserFromUserId(int userId, String serverId) throws ResumeNotFoundException, TException;
public TUser getUserFromUsername(String username, String serverId) throws ResumeNotFoundException, TException;
public TResume getPartialActiveProfileFromUserId(int userId, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException;
public TResume getPartialActiveProfileFromUsername(String username, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException, TException;
}
Code AspectJ :-
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
Object ret;
Throwable ex = null;
StopWatch watch = new Slf4JStopWatch();
try {
ret = proceed();
} catch (UserNotFoundException e) {
ex = e;
throw e;
} catch (ResumeNotFoundException e) {
ex = e;
throw e;
} catch (Throwable e) {
ex = e;
throw new RuntimeException(e);
} finally {
watch.stop(thisJoinPoint.toShortString());
if (ex != null) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
numEx++;
}
}
return ret;
}
}
Please help why this AspectJ is not working.
you can avoid catching the exceptions and just use a try/finally block without the catch.
And if you really need to log the exception you can use an after throwing advice, like this:
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
StopWatch watch = new Slf4JStopWatch();
try {
return proceed();
} finally {
watch.stop(thisJoinPoint.toShortString());
}
}
after() throwing (Exception ex) : call (* com.abc.Iface.* (..)) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
}
}
I'm afraid you cannot write advice to throw exceptions that aren't declared to be thrown at the matched join point. Per: http://www.eclipse.org/aspectj/doc/released/progguide/semantics-advice.html :
"An advice declaration must include a throws clause listing the checked exceptions the body may throw. This list of checked exceptions must be compatible with each target join point of the advice, or an error is signalled by the compiler."
There has been discussion on the aspectj mailing list about improving this situation - see threads like this: http://dev.eclipse.org/mhonarc/lists/aspectj-dev/msg01412.html
but basically what you will need to do is different advice for each variant of exception declaration. For example:
Object around() throws ResumeServiceException, ResumeNotFoundException, TException:
call (* Iface.* (..) throws ResumeServiceException, ResumeNotFoundException, TException) {
that will advise everywhere that has those 3 exceptions.
There is an "ugly" workaround - I found them in Spring4 AbstractTransactionAspect
Object around(...): ... {
try {
return proceed(...);
}
catch (RuntimeException ex) {
throw ex;
}
catch (Error err) {
throw err;
}
catch (Throwable thr) {
Rethrower.rethrow(thr);
throw new IllegalStateException("Should never get here", thr);
}
}
/**
* Ugly but safe workaround: We need to be able to propagate checked exceptions,
* despite AspectJ around advice supporting specifically declared exceptions only.
*/
private static class Rethrower {
public static void rethrow(final Throwable exception) {
class CheckedExceptionRethrower<T extends Throwable> {
#SuppressWarnings("unchecked")
private void rethrow(Throwable exception) throws T {
throw (T) exception;
}
}
new CheckedExceptionRethrower<RuntimeException>().rethrow(exception);
}
}