java - Throwing an exception to indicate element not found -
in below code i'm throwing exception if element not found in 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[]) { seek { string res = new testexception().findid("1"); system.out.println(res); } grab (exception e) { e.printstacktrace(); } seek { string res = new testexception().findid("11"); system.out.println(res); } grab (exception e) { e.printstacktrace(); } } private string findid(string id) throws exception { for(string str : strlist){ if(id.equalsignorecase(str)){ homecoming str; } } throw new exception("exception thrown - element not found"); } }
when run output :
1 java.lang.exception: exception thrown - element not found @ com.fmr.fc.portlet.actionabledashboard.throttling.testexception.findid(testexception.java:40) @ com.fmr.fc.portlet.actionabledashboard.throttling.testexception.main(testexception.java:24)
to maintain code volume low in asking question i'm throwing exception throw custom exception. reason i'm throwing exception custom exception caught farther phone call stack indicate error.
but bad practice throwing exception in way - findid throwing exception if id not found ?
yes, bad practice. should write function passes boolean , allow programme utilize determine do.
exceptions should utilize handle rare, unavoidable events. shouldn't part of standard logic of code, (surprise!) exception rule. things might (possibly) happen, unlikely , really, couldn't find way stop them.
java design-patterns
No comments:
Post a Comment