C # exception handling

While working on the project, I realized that there is something that I really do not know about C # (and I can not find anything about it in google). If you assign a value to a variable (which has already been initialized with a default value), and the value is created by another method, what will happen if you get an exception in another method. For clarification, here is an example:

eType = defaultvalue;
...
eType = (EReaderType)Enum.Parse(typeof(EReaderType), tXmlNode.InnerText, true);

What happens if Enum.Parse fails to parse the value (a string in Xml, not relevant here ...) and throw an exception? Will eType keep the default value or reassign something else (zero or some undefined blabla)? So far, my tests show that it will retain the old value. However, I'm not sure if this will work all the time or if it happens by accident. Simply put, I don't know how C # handles this stuff.

Edit: Ok, thanks for all the answers :)

+3
source share
5 answers

The correct way of reasoning:

  • side effects of subexpressions are performed from left to right.
  • Side effects of statements are performed in order of priority.

Suppose you have:

M().x = N(P()).Q(); // x is a variable

The order in which events occur:

  • M()
  • x
  • P()
  • N()
  • Q()
  • x

, , , .

+8
+17

Variable , eType = ( ) , ( )

+2

.

:

var x = SomeOperation();

:

  • SomeOperation .
  • x.

If an exception is thrown within SomeOperation, then step 1 above does not reach completion. This means that step 2 is never achieved.

This is a guaranteed, deterministic order of events, as far as I know. Therefore, you do not need to worry about xunexpectedly gaining some unpredictable value.

+2
source

As far as I know, this will throw an exception during the second allocation, which will ultimately not save the new value, keeping the old

+1
source

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


All Articles