DEV Community

Jesse Phillips
Jesse Phillips

Posted on

Raise Exceptions in D

I had a desire to throw exceptions in my Python script. Well here is what you need to know in D.

throw new Exception("Error message.");

import std.exception;
enforce(true, "Error message");
Enter fullscreen mode Exit fullscreen mode

The standard library provides a function to check a condition, if false it throws with the error message.

It is also possible to specify a custom exception to utilize. In D anything deriving from Throwable can be thrown or caught. Error derives from Throwable and is not intended to be caught as the compiler may not unwind the stack, thus not calling except handling code (no guarantee the catch will be called).

class MyException : Exception {
... /// https://tour.dlang.org/tour/en/basics/exceptions
} 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)