Also, you should catch specific exceptions rather than the generic Exception:
try
somevar3 := somevar2 / maybezero;
except
on EDivideByZero do
somevar3 := 0;
end;
end;
Just in case something else happened that you should be aware of.
Yes, but if you use *specified* exceptions do it like this:
try
somevar3 := somevar2 / maybezero;
except
on EDivByZero do
somevar3 := 0
else begin
{$ifopt D+}Showmessage(e.message);{$endif} // what's all this then?
Raise; // if it is NOT a division by zero, it is something else, so re-raise...Hopefully your program catches it elsewhere....
end;
end;
end;
Or like this:
try
somevar3 := somevar2 / maybezero;
except
on EDivByZero do
somevar3 := 0
else
Application.HandleException; // a (semi-)safe way to terminate in worst case scenario's in a Lazarus program (abort.. continue)
end;
end;
With the use of *specified* exceptions come responsibilities....
Reason: How can you catch what you do not name? In the best case the exception (other than a EDivByZero) will get eaten (ignored) in the worst case you just wrote code that you can hardly debug.
Production code is often more complex than this, but hardly, very limited, (should) use exceptions. The matter is really not trivial. Programmers think it is trivial, but it is not!
Rule book:1. What can cause an exception here? (If you KNOW that, you don't need an exception handler, but proper code!)
2. Can I mitigate without brute force? (using exceptions is brute force!)
3. If so, act like a programmer: solve it without exception use.
4. If you can NOT predict the exception, then use an exception handler during development. Observe what happens and
goto 2)
5. If all else fails, you are allowed to use exceptions in production code...Because they will be true exceptions...And won't occur much...if at all...
Example: testing the divisor for zero 1.000.000 times (one cycle on most processors) is usually cheaper than handling EDivByZero just 1 time, if you
know it is going to happen beforehand.
Since you named your divisor "maybezero" you just disqualified yourself to use exceptions in any meaningful way....
BTW: Handoko showed above how to solve this properly.