How to use exceptions

Christian Köstlin christian.koestlin at gmail.com
Sat Aug 13 13:36:08 UTC 2022


On 13.08.22 15:00, kdevel wrote:
> On Friday, 12 August 2022 at 21:41:25 UTC, Christian Köstlin wrote:
> 
>> which would enable something like
>>
>> ```d
>>     return  s
>>         .readText
>>         .parseJSON
>>         .contextWithException((UTFException e) {
>>             return new Exception("Cannot process UTF-8 in config 
>> file%s\n  %s".format(s, e.msg), e);
>>         })
>>         .contextWithException((FileException e) {
>>             return new Exception("Cannot process config file%s\n 
>> %s".format(s, e.msg), e);
>>         });
>> ```
> 
> This is not as DRY as it could be. Furthermore I would try implement the 
> error handling completely outside the main execution path, ideally in a 
> wrapper around a the old main function (renamed to main_). This approach 
> becomes problematic if exceptions of the same class can be thrown from 
> two functions of the chain. >
> Your code is printing e.msg. How to you localize that string?
Those 3 points are exactly touching the problems (I am ignoring the DRY 
thing for now, as this is a side battle):
1. error handling in main path: exactly thats what I would like todo. 
but for that the errors that raise need to have meaningful information. 
this is exactly what I am trying in those context* functions ... they do 
not do error handling, but more something like error enhancement (by 
fixing up the error information).
2. yes ... for that the chain would need to be broken up, then you can 
react on the same exception classes of different members of the chain 
differently ... for that I do not see a nice way to write it in d.
3. localization is a fantastic example of data that needs to be added to 
almost every exception that raises from below. my example with the 
strings is just an example, it could also be that by conventions of your 
application framework all context* functions raise 
LocalizableExceptions, that somehow can then be mapped to different 
languages with their own api. the generalalized main function then would 
handle those exception classes differently from "normal" exceptions.

hope that makes sense.

kind regards,
christian





More information about the Digitalmars-d-learn mailing list