Exceptions are not return types; exceptions indicate an error in the method and that it cannot continue.
Your actual example 2 returns nothing, the compiler knows that it will always throw an exception, so it does not need to worry about returning.
If you have:
public string foo(int something) { if(something > 10){ throw new NotImplementedException("Hello Stackoveflow!"); } }
he will complain because you are not returning the value all the time.
Also, from your example, if you had: string val = something() in your code, val will never be set, because the exception is not a return value.
However, this is a valid code, your function can either return a value based on its signature, or throw an exception. Anyway, you can expect warnings from the compiler. I'm not sure about C #, but in java, if you have code that is defined as unreachable, you will get warnings, for example:
public string foo(int something) { throw new NotImplementedException("Hello Stackoveflow!"); return "OK"; }
This code will give you a warning because this method cannot reach the return statement (but it is still valid code, at least if it was Java).
mikeb source share