TimerTask抛不出运行时异常

用J2SE和Android,都运行相同的TimerTask,表现

1. Java代码

import java.util.Timer;
import java.util.TimerTask;

public class ddd {

    public static void main(String[] args) throws Exception {
        Timer timer = new Timer();
        timer.schedule(new Task(), 10, 1000);
    }

    static class Task extends TimerTask {

        public void run() {
            System.out.println("**");
            int i = 5 / 0;
            System.out.println(i);

        }

    }

}

2. Andrdoi代码

import android.app.Activity;
import android.os.Bundle;

import java.util.Timer;
import java.util.TimerTask;

public class ddd extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Timer timer = new Timer();
        timer.schedule(new Task(), 10, 1000);
    }

    static class Task extends TimerTask {

        public void run() {
            System.out.println("**");
            int i = 5 / 0;
            System.out.println(i);

        }

    }
}

 表现为,J2SE程序会因java.lang.ArithmeticException: / by zero挂掉。Android程序会每隔一秒打印一行“**”,就是说错误代码没有抛出异常,而是被简单的忽略掉。

所以,开发TimerTask时要小心的处理异常,把可能抛出的异常都catch住处理掉。

展开阅读全文

TimerTask 定时器类问题...抛java.lang.NullPointerException异常

08-26

这个是我的源码rn[code=Java]rnpublic class MemConnectTestTimer rn /**rn * 测试mem连接是否有效rn */rn public static void testMemConnect()rn rn if (logger.isInfoEnabled())rn rn logger.info("ento the testMemConnec()");rn rn rn //获取定时时间间隔rn int time = Integer.parseInt(900000);rn rn //初始化定时类rn Timer timer = new Timer();rn rn //定时检测,tomcat启动10s后启动rn timer.schedule(new MemTask(), 10000,time);rn rn if (logger.isInfoEnabled())rn rn logger.info("exit the testMemConnec()");rn rn rnrnrnpublic class MemTask extends TimerTaskrnrn rn /**rn * 日志信息rn */rn private static UCDLog logger = LogManager.getLog(Contants.COMMON_LOG);rn rn //获取缓存类实例rn private static MyMemcached memcached = MyMemcached.getInstance();rn rn /**rn * 重载TimerTask的run方法rn */rn public void run()rn rn //记录入口日志rn if (logger.isInfoEnabled())rn rn logger.info("Begin to test memcached......");rn rn rn //如果插入数据失败,则重新初始化缓存类rn if (!memcached.addData("test", "test"))rn rn memcached.reInit("test", "test");rn rn rn //记录出口日志rn if (logger.isInfoEnabled())rn rn logger.info("Exit from test memcached.");rn rn rn rnrn[/code]rnrn有时候看日志的时候会抛这样一个异常:rn2011-08-26 15:58:35,035 INFO [Timer-0] [? run] Exit from test memcached.rnException in thread "Timer-0" java.lang.NullPointerExceptionrn at com.huawei.internet.util.MemTask.run(Unknown Source)rn at java.util.TimerThread.mainLoop(Timer.java:512)rn at java.util.TimerThread.run(Timer.java:462)rnrn是不是我的类哪里写得不够好 论坛

没有更多推荐了,返回首页