java 异常 方法,Java在方法中引发异常的最佳方法

本文探讨了在Java中创建自定义异常并将其应用于方法的正确方式。作者询问了当前实现是否是最优做法,以及是否需要在方法签名中声明异常。文章提到了检查异常和未检查异常的区别,并指出如果创建的是检查异常,则必须在方法头中声明;如果是未检查异常(如继承自RuntimeException的异常),则不需要显式声明。
摘要由CSDN通过智能技术生成

I have created my own type of exception and want to implement it in a method. As of now I have written it in the following way, and it works.

public Worker remove (String firstName, String lastName, String number) throws NoSuchEmployeeException {

Worker w = null;

for (int i = 0; i < list.size(); i++) {

if (list.get(i).getFirstName().compareTo(firstName) == 0 &&

list.get(i).getLastName().compareTo(lastName) == 0 &&

list.get(i).getNumber().compareTo(number) == 0) {

w = list.get(i);

list.remove(i);

}

else

throw new NoSuchEmployeeException(/*"Employee could not be found"*/);

}

return w;

}

What I would like to know is if this is the best way to do it or if there is any other more appropriate/efficient/correct way of doing it. And also, do I need to declare the exception in the method header?

Thanks in advance.

解决方案

I'm not going to comment on whether or not to use checked vs unchecked exceptions as that will provoke a monster debate.

If you create a checked exception, then yes it must be thrown in the method signature. If you create an unchecked e.g. extends from RuntimeException then you do not need to throw it in the method signature.

Checked exceptions are generally exceptions that are recoverable.

Unchecked exception are irrecoverable.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值