What's the equivalent of std::runtime_error in D?
Ali Çehreli
acehreli at yahoo.com
Wed Nov 9 16:27:45 UTC 2022
On 11/9/22 05:47, MorteFeuille123 wrote:
> class VKException : Exception
> {
> this(string msg)
> {
> super(msg);
> }
> }
>
> void _()
> {
> if (vkCreateInstance(&createInfo, null, &instance) != VK_SUCCESS) {
> throw new VKException("cannot create VK instance")
> }
> }
I enjoy exceptions a little differently:
1) I rarely define my own exception types because most of the time I
(and the user) care only about a meaningful error message.
(Having said that, during development, I sometimes print not
'exc.message' but 'exc' itself to view a stack trace even from an
Exception. (I always print 'exc' for Error objects because a stack trace
is almost the only thing for such programmer errors.))
2) I never see 'throw' in my code because I think std.exception.enforce
makes the code more readable (note that != is now ==):
enforce(vkCreateInstance(&createInfo, null, &instance) == VK_SUCCESS,
"cannot create VK instance");
'enforce' can throw special exception types as well:
enforce!VKException(/* ... */);
And for all vk* functions that should return VK_SUCCESS, the whole thing
can be wrapped in a function template but one needs to learn from
'enforce's implementation to ensure file and line numbers are reported
as well:
vkEnforce(vkCreateInstance(&createInfo, null, &instance),
"cannot create VK instance");
Ali
P.S. There is also the Learn forum, where such topics may be more
effective. :)
More information about the Digitalmars-d
mailing list