Example usage for java.lang ArithmeticException getMessage

List of usage examples for java.lang ArithmeticException getMessage

Introduction

In this page you can find the example usage for java.lang ArithmeticException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    int[] array = new int[] { 1, 0, 2 };
    int index = 0;
    try {/* w  w w .j a v  a  2 s.  c o  m*/
        System.out.println("\nFirst try block in divide() entered");
        array[index + 2] = array[index] / array[index + 1];
        System.out.println("Code at end of first try block in divide()");
    } catch (ArithmeticException e) {
        System.err.println("Arithmetic exception caught in divide()\n" + "\nMessage in exception object:\n\t"
                + e.getMessage());
        System.err.println("\nStack trace output:\n");
        e.printStackTrace();
        System.err.println("\nEnd of stack trace output\n");
    } catch (ArrayIndexOutOfBoundsException e) {
        System.err.println("Index-out-of-bounds exception caught in divide()\n"
                + "\nMessage in exception object:\n\t" + e.getMessage());
        System.err.println("\nStack trace output:\n");
        e.printStackTrace();
        System.out.println("\nEnd of stack trace output\n");
    } finally {
        System.err.println("finally clause in divide()");
    }
    System.out.println("Executing code after try block in divide()");
}

From source file:com.aegiswallet.utils.BasicUtils.java

public static BigInteger toNanoCoins(final String value, final int shift) {

    try {// w  w  w.j a v  a  2  s .c om
        final BigInteger nanoCoins = new BigDecimal(value).movePointRight(8 - shift).toBigIntegerExact();

        if (nanoCoins.signum() < 0)
            throw new IllegalArgumentException("negative amount: " + value);
        if (nanoCoins.compareTo(NetworkParameters.MAX_MONEY) > 0)
            Log.e(TAG, "AMOUNT TOO LARGE");

        return nanoCoins;
    } catch (ArithmeticException e) {
        Log.d(TAG, e.getMessage());
        return BigInteger.ZERO;
    }
}

From source file:ja.ohac.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//  ww  w  . j  ava2  s  .c o m

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final BigInteger rate = GenericUtils.parseCoin(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, rate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.dopecoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float leafBtcConversion,
        final String userAgent, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//from   w  w  w .ja v a2s . c o  m

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger leafRate = btcRate.multiply(BigDecimal.valueOf(leafBtcConversion))
                                        .toBigInteger();

                                if (leafRate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, leafRate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:de.jdellay.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float ccnBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//from  www.  j  a v  a 2 s  . co m

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger ccnRate = btcRate.multiply(BigDecimal.valueOf(ccnBtcConversion))
                                        .toBigInteger();

                                if (ccnRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, ccnRate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//w  ww.  jav a  2  s .com

    try {

        Double btcRate = 0.0;
        boolean cryptsyValue = true;
        Object result = getCoinValueBTC();

        if (result == null) {
            result = getCoinValueBTC_BTER();
            cryptsyValue = false;
            if (result == null)
                return null;
        }
        btcRate = (Double) result;

        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                double rateForBTC = Double.parseDouble(rateStr);

                                rateStr = String.format("%.8f", rateForBTC * btcRate).replace(",", ".");

                                final BigInteger rate = GenericUtils.toNanoCoins(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, rate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }

                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            //Add Bitcoin information
            if (rates.size() == 0) {
                int i = 0;
                i++;
            } else {
                rates.put(CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(String.format("%.8f", btcRate).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
                rates.put("m" + CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate("m" + CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(
                                        String.format("%.5f", btcRate * 1000).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
            }

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {

        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.espertech.esper.epl.agg.BigDecimalAvgAggregator.java

public Object getValue() {
    if (numDataPoints == 0) {
        return null;
    }//w  w w . j  a  v a 2  s  .c o  m
    try {
        return sum.divide(new BigDecimal(numDataPoints));
    } catch (ArithmeticException ex) {
        log.error("Error computing avg aggregation result: " + ex.getMessage(), ex);
        return new BigDecimal(0);
    }
}

From source file:com.espertech.esper.epl.agg.aggregator.AggregatorAvgBigDecimal.java

public Object getValue() {
    if (numDataPoints == 0) {
        return null;
    }/*from   w  w w  . j  ava2 s .com*/
    try {
        if (optionalMathContext == null) {
            return sum.divide(new BigDecimal(numDataPoints));
        }
        return sum.divide(new BigDecimal(numDataPoints), optionalMathContext);
    } catch (ArithmeticException ex) {
        log.error("Error computing avg aggregation result: " + ex.getMessage(), ex);
        return new BigDecimal(0);
    }
}

From source file:eu.cloudwave.wp5.feedbackhandler.aggregations.strategies.RequestAggregationStrategyImpl.java

/**
 * {@inheritDoc}//from w  w w. j av a 2s  .com
 */
@Override
public RequestAggregationValues aggregate(RequestCollector requests) {
    double expectedCount = getExpectedNumberOfMeasurementValueGroups();

    /*
     * Group by aggregation interval and create summary statistics with min, avg, max and count
     */
    Collection<Long> groupedByAggregationInterval = requests.getReqTimestamps().stream()
            .collect(Collectors.groupingBy(
                    timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
                    Collectors.counting()))
            .values();
    int calculatedCount = groupedByAggregationInterval.size();

    try {
        if (calculatedCount != 0) {
            // use integer summaryStatistics to get min, avg, max
            IntSummaryStatistics stats = groupedByAggregationInterval.stream().mapToInt(p -> toInt(p))
                    .summaryStatistics();

            // no time range selected, just return int summary
            if (expectedCount == 0) {
                return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(),
                        stats.getSum(), stats.getCount());
            } else {
                // if calculated count != expected count --> adjust minimum, average and count value
                if (Double.compare(calculatedCount, expectedCount) != 0) {
                    double newAverage = (double) (stats.getSum() / expectedCount);
                    return new RequestAggregationValuesImpl(0, stats.getMax(), newAverage, stats.getSum(),
                            (int) expectedCount);
                } else {
                    return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(),
                            stats.getSum(), (int) expectedCount);
                }
            }
        } else {
            return new RequestAggregationValuesImpl(0, 0, 0, 0, 0);
        }
    } catch (ArithmeticException e) {
        System.out.println(e.getMessage());
        return new RequestAggregationValuesImpl(0, 0, 0, 0, 0);
    }
}

From source file:com.dotosoft.dot4command.config.xml.XmlConfigParserTestCase.java

@Test
public void testExecute2c() throws Exception {

    try {//from  w  w w  .ja v a  2  s  .co m
        catalog.getCommand("Execute2c").execute(context);
    } catch (ArithmeticException e) {
        assertEquals("Correct exception id", "3", e.getMessage());
    }
    assertThat(context, hasLog("1/2/3"));

}