java thread 异常_Java Thread异常的处理方式

run()方法不允许throw exception,因此所有的异常必须在run()方法内进行处理。

方式一:使用try-catch

package study.thread.exceptiontest;

/**

*

* 使用try-catch处理线程异常

*

*/

public class ExceptionHandle1 implements Runnable {

@Override

public void run() {

int num = 0;

try {

num = Integer.parseInt("TTT");

} catch (Exception e) {

e.printStackTrace();

}

System.out.println("num = " + num);

}

public static void main(String[] args) {

ExceptionHandle1 t1 = new ExceptionHandle1();

Thread thread = new Thread(t1);

thread.start();

}

}

执行结果如下

java.lang.NumberFormatException: For input string: "TTT"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:580)

at java.lang.Integer.parseInt(Integer.java:615)

at study.thread.exceptiontest.ExceptionHandle1.run(ExceptionHandle1.java:14)

at java.lang.Thread.run(Thread.java:748)

num = 0

方式二:使用Thread类中setUncaughtExceptionHandler()方法

在异常发生的时候,传入的UncaughtExceptionHandler接口实现类中的uncaughtException()方法会被调用。

package study.thread.exceptiontest;

import java.lang.Thread.UncaughtExceptionHandler;

/**

*

* 异常处理的方式,自定义实现

*

*/

public class UncaughtExceptionHandlerDemo implements UncaughtExceptionHandler {

@Override

public void uncaughtException(Thread t, Throwable e) {

System.out.println("An exception has been captured");

System.out.printf("Thread: %s\n", t.getId());

System.out.printf("Exception: %s:%s\n", e.getClass().getName(), e.getMessage());

System.out.println("Stack Trace:");

e.printStackTrace(System.out);

System.out.printf("Thread status:%s\n", t.getState());

}

}

package study.thread.exceptiontest;

public class ExceptionHandle2 implements Runnable {

@Override

public void run() {

int num = Integer.parseInt("TTT");

System.out.println("num = " + num);

}

public static void main(String[] args) {

ExceptionHandle2 t1 = new ExceptionHandle2();

Thread thread = new Thread(t1);

thread.setUncaughtExceptionHandler(new UncaughtExceptionHandlerDemo());

thread.start();

}

}

执行结果如下

An exception has been captured

Thread: 11

Exception: java.lang.NumberFormatException:For input string: "TTT"

Stack Trace:

java.lang.NumberFormatException: For input string: "TTT"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:580)

at java.lang.Integer.parseInt(Integer.java:615)

at study.thread.exceptiontest.ExceptionHandle2.run(ExceptionHandle2.java:7)

at java.lang.Thread.run(Thread.java:748)

Thread status:RUNNABLE

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值