Exceptions handling trouble - exception

Trying to add divide by zero exception in my calculator project through the try/catch block:
private class Calculate implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
if (operation.equals("/")) {
display.setText(Double.toString(getResult() / Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("*")) {
display.setText(Double.toString(getResult() * Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("-")) {
display.setText(Double.toString(getResult() - Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("+")) {
display.setText(Double.toString(getResult() + Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
if (display.getText().endsWith(".0")) {
display.setText(display.getText().replace(".0", ""));
}
calculationMade = true;
operation = "";
}
catch (IllegalArgumentException exc) {
display.setText("You cannot divide by zero!");
}
}
}
But in this way it still writes me "Infinity" in a text field. Can anybody suggest where i'm wrong please?

When working with double, zero division returns Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY (depending on operand signs)
System.out.println(1.0d/0d);
System.out.println(-1.0d/0d);
System.out.println(1.0d/-0d);
System.out.println(-1.0d/-0d);
Only non-decimal arithmetic throws an exception on zero division. And the exception is not an IllegalArgumentException but an ArithmeticException.

Related

Why RuntimeException not stop execution with finally block?

I ask an help to understand why this difference of behavior.
public class Test3 {
public static void main(String[] args) {
Double d = new Test3().findPrice$withoutFinally();
//Double d = new Test3().findPrice$withFinally();
System.out.println(d);
}
private double findPrice$withoutFinally() {
double price = -1.0;
int attempt = 0;
do {
try {
price = getPrice();
}
catch (MyException e) {
System.out.println("Caught MyException!");
}
attempt++;
} while (attempt < 3);
return price;
}
private double findPrice$withFinally() {
double price = -1.0;
int attempt = 0;
do {
boolean retry = false;
try {
price = getPrice();
}
catch (MyException e) {
System.out.println("Caught MyException!");
}
finally {
System.out.println("finally");
if (retry) {
System.out.println("retrying...");
attempt++;
} else {
break;
}
}
} while (attempt < 3);
return price;
}
private Double getPrice() throws MyException {
if (true) {
throw new RuntimeException("Testing RE");
}
return null;
}
}
I mean this, running findPrice$withoutFinally() method I got:
Exception in thread "main" java.lang.RuntimeException: Testing RE
that is the behaviour thah I expect. But running findPrice$withFinally() method I got this unexpected (for me!) behaviour:
finally
-1.0
findPrice$withFinally() should not behave as findPrice$withoutFinally() and then stop execution because of the exception?
Thanks!
finally block is executed ALWAYS - when there is an exception and when there is no exception

Assert null is not working as actual method changes the value

I am trying to write a Junit for a piece of code for asserting the value as null. But the value is changing on the actual call.
Main Class Code
#Activate
public void activate(ComponentContext context)
{
myNotificationSubscriber = NotificationSubscriber.newInstance(myGlobalTableNotificationService,
NotificationType.ENTITIES,
this);
setWantedSubscriptionStatus();
LOG.debug("Activating {} service", getClass().getName());
try
{
applyConfigUpdate(context, IS_ACTIVATION);
}
catch (ServiceNotAvailableException e)
{
String instanceNameWithException = COUNTER_INSTANCE_COBA.concat("-")
.concat(String.valueOf(e.getResponseCode().getResponseCode()))
.concat(e.getClass().getSimpleName());
myCounterregistrator.get()
.incrementCounter(Counter.DATAACCESS_COBA_RESPONSE_UNSUCCESSFUL.getCounterInstance(instanceNameWithException));
LOG.debug("Can not activate Component :{}", e.getMessage());
}
LOG.info("COBA Cache state is {}", myCacheState);
}
private GlobalTableRetriever getGlobalTableRetrieverer() throws ServiceNotAvailableException
{
GlobalTableRetriever tableFetcher = myGlobalTableRetriever.get();
if (tableFetcher == null)
{
throw new ServiceNotAvailableException(RETRIEVER_SERVICE_NOT_AVAILABLE_MSG, ResponseCode.COBA_READ_DATA_TEMPORARY_ERROR);
}
return tableFetcher;
}
I want to write the test for the catch block. So tried to write the test case in below.
#Test
public void testapplyConfigUpdate() throws GlobalTableException
{
exception.expect(ServiceNotAvailableException.class);
globalTableRetriever.set(null);
tableFetcher = globalTableRetriever.get();
assertThat(tableFetcher).isNull();
myTableHandler.activate(myOsgiComponentContext);
verify(myCounterRegistratorService, times(1)).incrementCounter(any(CounterInstance.class));
}
But once its entering to getGlobalTableRetrieverer method, the assertion null value is changing to original.
Why do you even need to assert that?
exception.expect(ServiceNotAvailableException.class);
already implies that tableFetcher is null.
Just try this :
#Test
public void testapplyConfigUpdate() throws GlobalTableException
{
exception.expect(ServiceNotAvailableException.class);
globalTableRetriever.set(null);
tableFetcher = globalTableRetriever.get();
}

how to solve Arithmetic Exception in java

Below is my code :
public class prg34 {
public static void main(String[] args) {
int a=6;
for(int i=0;i<10;i++){
System.out.println(a/i);
}
}
}
Exception:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at run.prg34.main(prg34.java:8)
How to solve above Arithmetic Exception in java ?
You are trying to divide by zero in your first iteration. Change your first condition of i = 0, to something other than zero.
You cannot divide by 0, as I believe Java handles the division by zero error by a processor exception which triggers an interrupt.
Your first iteration is trying 6/0.
public static void main(String[] args) {
int a=6;
for(int i=1;i<10;i++){
System.out.println(a/i);
}
}
The first loop in your code gives an exception because you are trying to divide 6 by 0 i.e the ArithmeticException.
In order to fix this you must have to use try catch block. I've illustrated full code here. Please fix this.
public class prg34 {
public static void main(String[] args) {
int a=6;
try {
for(int i = 0; i < 10; i++) {
System.out.println(a/i);
}
}catch(ArithmeticException e) {
System.out.println("Division by zero is not possible. "+ e);
}
}
}

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

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