(Ab)use of Try..Except

Today I found an example of the abuse of a try.. except block.

The idea is simple. StrToInt converts a string to an integer as long as the string contains an integer value. If not an exception will be raised.
This exception will be caught because of the try..except block and 0 will be assigned to the variable iValue.

Please, never write code like this! The problem is that all kind of exceptions will be caught including EAccessViolation, EOuOfMemory etc..
Certainly is is better to use a function instead of StrToInt that doesn’t throws an exception but allows you to use a default value.

If there is no other way, if you have to call a function that possibly raises an exception then catch only this particular exception. In our example we have to catch the EConvertError.

This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.