'while' statement cannot complete without throwing an exception - Android

KiKo picture KiKo · Jan 23, 2015 · Viewed 15.4k times · Source

With this method I'm updating TextView every second.

 private void UpdatingTime(final String endTime, final long diffInDays) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(ONE_SECOND);
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // Updating time every second
                                    long diffInHours = Methodes.diffInHours(endTime, diffInDays);
                                    long diffInMinutes = Methodes.diffInMinutes(endTime, diffInDays, diffInHours);
                                    long diffInSeconds = Methodes.diffInSeconds(endTime, diffInDays, diffInHours, diffInMinutes);

                                    tvTime2.setText(addZeroInFront(diffInHours)
                                            + ":" + addZeroInFront(diffInMinutes)
                                            + ":" + addZeroInFront(diffInSeconds));
                                }

                                private String addZeroInFront(long diffInHours) {
                                    String s = "" + diffInHours;
                                    if (s.length() == 1) {
                                        String temp = s;
                                        s = "0" + temp;
                                    }
                                    return s;
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

This method is working perfect. But I got this warning:

'while' statement cannot complete without throwing an exception.

Reports for, while, or do statements which can only exit by throwing an exception. While such statements may be correct, they are often a symptom of coding errors.

I hate warnings and I want to fix it. How can i fix this warning, or there is a better solution for this infinite loop...?

Answer

SLaks picture SLaks · Jan 23, 2015

This warning is a false positive; you should ignore it.

Usually, an infinite loop is a sign of a mistake somewhere; in your code, an infinite loop is exactly what you want.