Reputation: 1250
If I want to build my business logic, is it a better practice to handle the logic by throwing custom exceptions or by adding specific "If" conditions to avoid a specific case?
For instance (stupid, but simple example to get the point):
var success = true;
try{
if(value == 5){
throw new CustomException("Invalid Value!");
}
DoStuffIfValueIsValid();
}catch(CustomException e){
success = false;
}
return success;
VS
var success = true;
if(value == 5){
success = false;
} else {
DoStuffIfValueIsValid();
}
return success;
I know that this example looks stupid, but in a large scale of code with a lot more logic, should I use more conditions to avoid using multiple try catch?
Thanks in advance!
Upvotes: 1
Views: 1729
Reputation: 20320
You should try to only throw an exception if you can't deal with it at the point it's detected
try
{
// some stuff
if (condition)
{
throw new MyException("ooher");
}
}
catch (MyException mex)
{
// undo some stuff
throw;
}
Upvotes: 0
Reputation: 44306
Both ways are valid and it really depends on what else that code is responsible for.
First one is when it is exceptional, there's just no logical way to carry on. Though given your example you wouldn't normally throw and catch your own exception within 1 method. Usually you need it so you can unwind the call chain to a point where you can deal with the failure.
Second way ( which should be your first option if you can do it ) is that if you can logically handle error conditions, do so.
Also the second option is often handled as a "guard clause"
usually written like :-
if(value == 5) return false;
DoStuffIfValueIsValid();
Upvotes: 1
Reputation: 216312
Simply said, I suggest to not use exceptions to control the flow of a program. You should raise an exception when there is no other options to solve the problem, not to jump to a particular point of your program just to return a result or another. Exceptions are reserved for 'exceptional' or unexpected situations. Doing in that way is a bit like writing a goto
. Apart from that, they are expensive objects that could have a significant impact on performance. See this article on MSDN 'Avoid using exceptions for control flow' in NET Framework Performance Rules book.
Upvotes: 3