How to use exceptions

kdevel kdevel at vogtner.de
Sat Aug 13 15:00:36 UTC 2022


On Saturday, 13 August 2022 at 13:36:08 UTC, Christian Köstlin 
wrote:
> [...]
> 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).

"Exception enrichment" would be my wording which is supported by 
google [1].
There is also the notion of "exception context" [2] and 
"contexted exception" [3].

> 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.

The current filename imposes a context on its processing. The 
exception thrown from readText knows that filename and propagates 
it within the exception msg. Unfortunately exceptions are 
frequently only "stringly typed", e.g.

394: throw new JSONException("JSONValue is not a number type");
406: throw new JSONException("JSONValue is not a an integral 
type");

This should have been made into an exception hierarchy with the 
faulty value beeing a data member of the respective class. That 
would nicely support the crafting of a message for the user in 
the presentation layer.

Of course the UTF8Exception must be enriched with the filename in 
the application code.

> 3. localization is a fantastic example of data that needs to be 
> added to almost every exception that raises from below.

How would you handle a FileException.msg = "myconfig.cnf: 
Permission denied"? Run regular expressions over the msg? 
Something is fundamentally wrong if any kind of parsing of error 
strings is required.

Then there is another type of user who shall not be faced with 
any kind of specific error message: The client of a company which 
runs a web application. This case is easy to implement: Catch any 
Exception and replace it with an "The Unforeseen happend, id#" 
message. Leave the code as it is and let the stack trace go into 
the error_log. The devops people of the company probably 
understand english messages.


[1] 
https://jenkov.com/tutorials/java-exception-handling/exception-enrichment.html

[2] 
https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.exceptioncontext?view=aspnet-mvc-5.2

[3] 
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/exception/ContextedException.html



More information about the Digitalmars-d-learn mailing list