Cannot invoke “java.net.URL.toExternalForm()“ because “location“ is null异常解决

在进行图形界面的设置时我们可能会遇到这样的异常情况:

Cannot invoke "java.net.URL.toExternalForm()" because "location" is null

为避免方法调用中空对象引用异常 `NullPointerException`,你可以通过判断该变量是否为 `null`,若为 `null` 则为其赋值一个默认值。例如:

  1. 1.使用try,catch捕捉异常

URL location = null;
if (location == null) {
try {
location = new URL("https://example.com"); //或获取实际有效地址
} catch (MalformedURLException e) {
e.printStackTrace();
}
}

  1. 2.通过三元操作符(ternary operator)判断 `location` 是否为 `null`,来赋默认值:


URL location = null;
location = (location == null) ? new URL("https://example.com") : location;

这样,你就可以在代码的其他部分中,安全地使用 `location` 变量进行方法调用:

String locationString = location.toExternalForm();

这将避免在调用 `toExternalForm()` 方法时,抛出空对象引用异常。

例如:我在编译是就遇到Cannot invoke "java.net.URL.toExternalForm()" because "location" is null异常

我的原来的代码是  :

 btnNewButton_1.setIcon(new ImageIcon(SchoolClassAddInterFrm.class.getResource(".ideab/reset.png")));

我用的方法是使用try,catch来解决,以下就是我修改之后的代码:

try {
            btnNewButton_1.setIcon(new ImageIcon(ImageIO.read(new File(".ideab/reset.png"))));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

在编译程序时。我们通常会遇到各种各样的异常情况,所以我们需要对try,catch有充分的理解。懂得如何捕捉异常情况,使得程序不报异常。在实际运用开发中,我们遇到的通常都是空指针异常。
     以上是我解决问题后自己的一点感悟,如有问题,望指正。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值