General C # Question

The following class has two methods in which M1 complains that not all code codes return a value, and M2 does not.

Question: How does the compiler resolve M2 in the context of the return value? As an instance of NotImplementedException is implicitly displayed as int (if there is any internal compilation time resolution)

class A { int M1() { } int M2() { throw new NotImplementedException(); } } 
+6
source share
4 answers

A method is not always required to return a value; in particular, it is also allowed to exit by throwing an exception (in this case, the value is not returned).

Edit: In particular, the rules for the method body that return int :

  • All return in a method must return an expression convertible to int
  • The end of the method block cannot be accessed.

In your example, the compiler can prove that M2 always exits by throwing, so the end of the method block is unavailable (satisfies rule No. 2). There are also no return that also satisfy rule # 1. Therefore, this is a valid method definition.

On the other hand, M1 does not satisfy rule # 2, therefore it is not legal.

You are probably mistaken in an error message that does not mention throwing at all, but consider that in almost all cases methods with return values ​​make return instead of throwing - the compiler just says that you probably want to forget to do it.

+7
source

Exceptions affect code flow. Any statements after the throw will not be executed, the compiler can prove this, therefore he is satisfied with the method.

An exception will not return an int , nothing will be returned in the usual sense. Instead, an exception is thrown; the CLR handles them differently.

http://msdn.microsoft.com/en-us/library/ms173160(v=vs.80).aspx

+2
source

The exception will not be passed as int. The compiler knows that this is an exception that will always be reached, so it does not complain. When an exception throws, it unwinds the stack into exception handling blocks or fails. Int will never be returned to the calling method.

0
source

As stated on MSDN ,

The throw operator is used to notify of an abnormal situation (exception) during program execution.

When the code is executed in the throw expression, the program stops and an exception message is displayed to the user (if the programmer has not specified any error handling logic)

0
source

Source: https://habr.com/ru/post/897218/


All Articles