-1

Note: This is a question from the PHP perspective for C#. Maybe it isn't the right way to do it, but here is what I'm trying to do.

Suppose you have defined:

void Die(string error){
 print(error);
 return; 
}

And you call it from another method:

void CallingFunction(){
  if(SomethingDoesNotCheckOut())
   Die("bla");

  // do stuff
}

is it possible to have Die() also trigger an early out in the "parent" method that calls it?


One example:

void CallingFunction(){
  if(index>arrayLength)
   Die("that's too big!");

  // do stuff
}

It seems try-catch is overkill for this, but I'd rather be able to just call a function that will just stop the current "parent" function. Maybe I'm thinking too much like PHP's die()

ina
  • 19,167
  • 39
  • 122
  • 201
  • 2
    What do you mean with _early out_ ? – Steve Jan 03 '18 at 09:13
  • 1
    Exceptions, `try` and `catch` are the best way to handle errors in C#. Return values are more C-Style. – lorisleitner Jan 03 '18 at 09:13
  • Looking at your title and code I think that you just need an else block when everything is ok – Steve Jan 03 '18 at 09:18
  • @Steve early out referring to an early return if some conditional checks out in advance – ina Jan 03 '18 at 09:19
  • You cannot _force_ a method to return early, even with exceptions. A method can always wrap a call to your method in `try`/`catch`. But, cooperatively, you can use exceptions to "unroll" the stack and get back to a caller higher up in the stack. See marked duplicates for details. In your scenario, `Die()` could throw an exception, and as long as `CallingFunction()` doesn't catch it, control will return to the next `catch` block in the call stack. – Peter Duniho Jan 03 '18 at 09:20
  • added an example... simple check of an index is within array length seems trivial... seems try/catch is overkill for it? – ina Jan 03 '18 at 09:21
  • Why not just `if (condition) { Die("message"); return; }`? – Camilo Terevinto Jan 03 '18 at 09:22
  • 1
    _if(somethingbad) { Die("reason"); return;} else { do stuff }_ – Steve Jan 03 '18 at 09:22
  • Why is try/catch overkill? Do you expect the condition to ever happen? You certainly shouldn't use exception-handling for normal flow control in your program, so if you intend an out-of-range value to be a legitimate state, you'll want a different mechanism. But your question doesn't explain how you'd get into that state, why you're handling it that way, nor what you've already tried and why that didn't work for you. – Peter Duniho Jan 03 '18 at 09:23
  • @Steve that doesn't seem elegant enough – ina Jan 03 '18 at 09:23
  • @PeterDuniho normally if i'm the operator that would never happen, but i'm trying to open source some code... so unknown repo user might let trivial cases like that happen – ina Jan 03 '18 at 09:24
  • What do I have to say? Beauty is in the eye of the beholder – Steve Jan 03 '18 at 09:24
  • so, this isn't a duplicate per se... updated the question to reflect why this would be a reasonable question for folks coming from PHP, even if the answer is just use exceptions – ina Jan 03 '18 at 09:26
  • 1
    If "unknown users" write buggy code because they don't understand control flow then that's their problem. There is no equivalent to "die" in C#, other than exceptions. For normal control flow, however, you should use `return`. Your example is a simple guard clause for a method, which is either an exception if it's severe enough or a simple return if it's not. Simply put, don't create a "die" method and you should be fine. If you need to log the fault, then make the method a logging method instead and nobody should think it would "force an early return" in the process. – Lasse V. Karlsen Jan 03 '18 at 09:27
  • @ina do not use the exceptions to simply drive your code flow. – Steve Jan 03 '18 at 09:27
  • _"unknown repo user might let trivial cases like that happen"_ -- then you are dealing with argument validation, and an exception would be appropriate. – Peter Duniho Jan 03 '18 at 09:27
  • Let me expand, simply put, don't try to reimplement php idioms in C#. PHP and C# have lots of different ways of doing things, any programmer coming from PHP to C# should learn C# and bring with him or her the things that is smart to bring over, but they should not force either language to be like the other, trying to do that will only fail. – Lasse V. Karlsen Jan 03 '18 at 09:28
  • Don't get concerned about elegancy. There are two main things a developer has to worry about: 1) Performance. 2) Minimum resource usage (Memory). – DotNet Developer Jan 03 '18 at 09:30
  • @Bahrom i thought c# is a managed language so you don't get much control on memory? – ina Jan 03 '18 at 09:31
  • Please don't use this comment thread to learn every difference between PHP and C# or bring up other topics, focus on the question at hand and if needs be open other questions, otherwise we can close this comment thread right now because it isn't suited for threaded conversation. – Lasse V. Karlsen Jan 03 '18 at 09:32
  • @LasseVågsætherKarlsen i respect your wisdom. i agree that php shouldn't be applied to C#, but to someone from PHP this is a valid "learning question" to ask on C#. i'm still trying to understand why people are downvoting. – ina Jan 03 '18 at 09:35
  • I think the main gripe here is that you didn't ask "I have this PHP code, how do I do something similar in C#" but instead "I have this PHP code, now I rewrote it to C#, how to make it behave like PHP". But I didn't downvote so it's only a guess. – Lasse V. Karlsen Jan 03 '18 at 09:40
  • Debug.Assert was actually what I was looking for – ina Jan 05 '18 at 04:32

2 Answers2

2

Not without throwing an exception, no. Bear in mind that in many cases the calling method will be non-void - in that case, what value would you expect it to return?

The use case you're describing does sound like it would be better handled with an exception anyway, to be honest. That's the C# idiomatic error handling mechanism.

If you want to collect errors without using exceptions, you'll have to return explicitly.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Usually you use exceptions for this purpose. Simply throw an Exception:

void Die(string error){
 print(error);
 throw new Exception(error); 
}

You can handle it any time by implementing a try ... catch at a higher level.

try
{
    // Something that can call Die.
}
catch (Exception ex)
{
    // Something threw an exception. Now handle it.
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325