简体   繁体   中英

Proper way of handling "not found" error case

I have a function getDeviceByAddress(String identifier) , that throws a DeviceNotFoundException if the identifier is not found. Also, I created getDeviceByAddressOrNull(String identifier) , that does not throw in an error case, but returns null.

Not I am wondering what the better architectural approach is. Should I use the exception like

try{
    Device device = getDeviceByAddress(...);
    ... do something with the device ...
}catch(DeviceNotFoundException){
    // device not found, nothing to do
}

or rather

Device device = getDeviceByAddressOrNull(...);
if(device == null){
    // device not found, nothing to do
    return
}
... do something with the device ...

I am tending towards the latter, since it's more explicit, but would like to hear opinions of more experienced developers.

It depends on the specific circumstances. Error handling is usually more resource-intensive, so if your function runs thousands of times every second in a resource-limited environment, you might want to choose the second option.

Otherwise error handling makes for more extensible code. With the second option you'll run in trouble later when you realise there are different reasons for not finding your device, and want to differentiate between them. The code is usually also easier to understand.

For this particular example, the second option is more readable, the code which handles the null device case is closer to the actual method call which gets the device.

In the exception handling case, the code which does something with the non-null device might expand over time and will draw the attention away from the null handling logic.

There are also other aspects I would consider. For example, I would look on the existing exception handling flow, for example if all the exceptions triggered by the system get monitored for debugging purposes I would rather go with that approach to follow the pattern and improve the code readability/understanding for other developers.

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