简体   繁体   中英

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. 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 ?

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. Some details here :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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