delphiunicodedelphi-2006

Pass WideString to raise an exception


How I can pass unicode string to exception raise messages and catch it:

try
  if some <> some2 then 
    raise Exception.Create('Cannot connect to Sever');
...
...

except
on E: Exception do 
   mError(E.Message);
   exit;
end;

The idea is localization.


Solution

  • You can declare an exception class that uses WideString rather than string. An excellent example of this can be found in the TNT Unicode library. Not only does this library introduce a Unicode exception class, it provides all the associated scaffolding needed to make the exception handling mechanisms deal with Unicode exceptions.

    For instance, suppose an exception raised that reaches the top level exception handler. You want that to be Unicode aware, and the TNT library ensures that. Or you want operating system errors to be localised. Again, there's some extra work involved and the TNT library takes care of it.

    My advice is that if you wish to work with Unicode in your application, in a pre-Unicode Delphi, you should adopt the TNT Unicode library. If for some reason you cannot adopt it, at least use its source code for inspiration in your own coding.