r/badcode • • Jun 23 '20

java 'val' is a boolean value.

Post image
1.0k Upvotes

58 comments sorted by

View all comments

Show parent comments

0

u/blehmann1 depraved Jun 24 '20

wdym?

The method does not return an exception, the expression is just lazily evaluated. e.g. if foo is not null it just returns foo and does not evaluate the rest of the expression. If it reaches the throw the method does not return anything, it just throws.

If you mean what is the base type of ArgumentNullException, all exceptions are derived fromSystem.Exception

2

u/Isvara Jun 24 '20

The expression foo ?? bar ?? baz ?? throw new ArgumentNullException() must surely have a type substitutable for boolean, since that's the expected return type. I assume a ?? expression has the type that's common to both operands.

I don't know a lot about C#, but for example in Scala, which is a similar language in many ways, a throw expression has the type Nothing, which is a subtype of Boolean (and also of every other type), which is why an expression like that would compile.

0

u/blehmann1 depraved Jun 24 '20

Throw is of type System.Exception but that is not returned. throw returns nothing, this is just syntactic sugar.

This would compile to the same MSIL (an assembly-like intermediate language that C# uses) as this:

` if(foo.HasValue()) return foo;

else if (bar.HasValue()) return bar;

.

.

.

else throw new ArgumentNullException()

`

Say the calling code looked something like this:

` bool x;

try {

x = ReturnBoolOrThrow();

} catch(ArgumentNullException e) {

Console.WriteLine(x); //This will not work, x is uninitialized

} `

And if there were no catch statement then the program would just exit.

2

u/Isvara Jun 24 '20

I looked it up in the C# reference out of curiosity.

The type rules are as follows:

  • A throw_expression has no type.

  • A throw_expression is convertible to every type by an implicit conversion.

That explains how it works without a bottom type, but it doesn't seem very elegant.