Java在方法中引发异常的最佳方法 [英] Java Best way to throw exception in a method

查看:165
本文介绍了Java在方法中引发异常的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了自己的异常类型,并想在方法中实现它.到目前为止,我已经按照以下方式编写了它,并且可以正常工作.

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?

谢谢.

推荐答案

我将不评论是否使用检查与未检查异常,因为这会引起一场激烈的辩论.

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

如果创建一个检查异常,则必须在方法签名中引发该异常.如果您创建未选中的内容,例如从RuntimeException扩展,则无需将其放入方法签名中.

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.

这篇关于Java在方法中引发异常的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆