Exception is thrown but exception.getMessage() is null

本文解答了一个关于Java异常处理的问题:当捕获异常并尝试显示其消息时遇到null值的情况。文章解释了使用toString()方法相较于getMessage()方法的优势,并提供了解决方案。

Q:

I am wirting a code in which an exception is thrown, I catch this exception in the catch block, but when I display e.getMessage() it displays null.....Can any body help in telling why....

 

A:

getMessage() is just about useless.
If you use the no-arg constructor for a Throwable, you'll get a null message.
Much, much better for displaying information about Throwables is toString() which will include the class name of the Throwable and the message if it's not null.
Out shop never uses getMessage()

 

RXTX报错java.lang.NullPointerException: Cannot invoke “String.split(String)” because “<local5>” is null thrown while loading gnu.io.RXTXCommDriver,win10 public class TestDemoDis { ReaderDisService service = new ReaderDisServiceImpl(); HandleReader reader = new HandleReader(); String readerName = "COM4:9600"; // 串口名称 private void connectDev() { try { // 设置协议类型 reader.setEnumProtocolType(EnumProtocolType.DISCRETE_OLD_PROTOCOL); // 设置串口名称和波特率 reader.setName(readerName); // 连接设备 boolean result = reader.connectDev(readerName); if (result) { System.out.println("连接成功"); // 获取版本信息 String version = service.version(reader); System.out.println("版本: " + version); // 写标签数据 byte[] epcData = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; boolean writeResult = service.writeTagData(reader, (byte) 1, (byte) 2, (byte) 3, epcData); System.out.println("写标签数据成功: " + writeResult); // 暂停一段时间 Thread.sleep(10000); // 停止盘存 service.stopInv(reader); // 断开设备连接 reader.disconnectDev(); } else { System.err.println("无法连接到设备: " + readerName); } } catch (NullPointerException e) { System.err.println("NullPointerException: " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); e.printStackTrace(); } } public static void main(String[] args) { TestDemoDis testDemoDis = new TestDemoDis(); testDemoDis.connectDev(); }
03-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值