Better branding of -betterC
Jacob Carlborg
doob at me.com
Sat Oct 31 07:12:47 UTC 2020
On 2020-10-29 22:57, Paul Backus wrote:
> I have a DIP I think you'll like:
>
> https://github.com/dlang/DIPs/blob/02594a09d9daf1d393ebce2cfc2f0c4f90d4bcf8/DIPs/1NNN-PJB.md
Your main rationale seems to be error handling without exceptions. In my
opinion there are better ways to deal with error handling than returning
errors. For example, there's nothing wrong with exceptions per se (well,
a few details), it's just that the implementation is a bit unfortunate.
In my opinion there's nothing that stops exceptions on being implemented
in some other way, that does not require the runtime. Like a Result
struct or as tagged unions with some help from the compiler.
The following code:
enum Error
{
fileNotFound
}
string readFile(string path) throw(Error)
{
throw Error.fileNotFound;
}
void foo() throw(auto)
{
string content = try readFile("foo.txt");
}
void bar()
{
try
bar();
catch (Error e)
writeln("An error occurred: ", e);
}
Can be lowered to something like:
struct Result(Value, Error)
{
Value value;
Error error;
bool isSuccessful;
this(Value value)
{
this.value = value;
isSuccessful = true;
}
this(Error error)
{
this.error = error;
isSuccessful = false;
}
}
Result!(string, Error) readFile(string path) nothrow
{
return Result!(string, Error)(Error.fileNotFound);
}
Result!(void, Error) foo() nothrow
{
string content;
auto __result = readFile("foo.txt");
if (__result.isSuccessful)
content = __result.value;
else
return Result!(void, Error)(__result.error);
}
void bar() nothrow
{
auto __result = bar();
if (!__result.isSuccessful)
writeln("An error occurred: ", __result.error);
}
Have a look at this C++ proposal [1] by Herb Sutter and the error
handling in Zig [2].
[1] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf
[2] https://ziglang.org/documentation/master/#Errors
--
/Jacob Carlborg
More information about the Digitalmars-d
mailing list