简体   繁体   English

引发异常以指示未找到元素

[英]Throwing an exception to indicate element not found

In below code I'm throwing an exception if an element is not found in a String list. 在下面的代码中,如果在字符串列表中找不到元素,则抛出异常。

import java.util.ArrayList;
import java.util.List;

public class TestException {

    private static List<String> strList = new ArrayList<String>();

    static {
        strList.add("1");
        strList.add("2");
    }
    public static void main(String argsp[]) {

        try {
            String res = new TestException().findId("1");
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String res = new TestException().findId("11");
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String findId(String id) throws Exception {

        for(String str : strList){
            if(id.equalsIgnoreCase(str)){
                return str;
            }
        }

        throw new Exception("Exception Thrown - element not found");

    }

}

when run output is : 当运行输出是:

1
java.lang.Exception: Exception Thrown - element not found
    at com.fmr.fc.portlet.actionabledashboard.throttling.TestException.findId(TestException.java:40)
    at com.fmr.fc.portlet.actionabledashboard.throttling.TestException.main(TestException.java:24)

To keep code volume low in asking question I'm throwing Exception but I will throw a custom exception. 为了保持较低的代码量,我抛出了Exception,但是我将抛出一个自定义的异常。 The reason I'm throwing an exception is that the custom exception is caught further up call stack to indicate an error. 我抛出异常的原因是自定义异常在调用堆栈中进一步捕获以指示错误。

But is it bad practice throwing an exception in this way - findId is throwing an exception if an id is not found ? 但是,以这种方式抛出异常是否不好?如果找不到id,findId就会抛出异常?

Yes, this is bad practice. 是的,这是不好的做法。 You should write a function that passes a boolean and allow the program to use this to determine what to do. 您应该编写一个传递布尔值的函数,并允许程序使用该函数来确定要执行的操作。

Exceptions should only be use to handle very rare, completely unavoidable events. 异常只能用于处理非常罕见的,完全不可避免的事件。 They shouldn't be part of the standard logic of your code, they are (surprise!) the exception to the rule. 它们不应成为代码标准逻辑的一部分,它们是(惊奇!)规则的例外。 Things that might (possibly) happen, but are very unlikely and you really, really couldn't find a way to stop them. 可能(可能)发生但不太可能发生的事情,您确实真的找不到阻止它们的方法。

In general it is bad practice to throw an exception in this type of situation. 通常,在这种情况下抛出异常是不好的做法。 Try modifying your function to return an Optional as used in the guava pattern. 尝试修改函数以返回番石榴模式中使用的Optional。 Some details here : 一些细节在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM