1

Not sure if this is possible or maybe considered bad practice, but I'm wondering if there's a nice way to write the above if statement in C#.

Something like...

if (method throws exception)
{
    // do something
}
else
{
    // do something else
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
BillMux
  • 73
  • 2
  • 6
  • well best practice would be to have your code in a try catch statement. and do something like: ``` try { A = Method(); B = Method2(); } catch(Exception) { // Exception is thrown } ``` Everything which is in your try will continue execute except if one exception is thrown. – WilliamW Jan 13 '20 at 10:08
  • Still unclear. What is `method` here? – canton7 Jan 13 '20 at 10:08
  • you can `catch` the exception (and `throw;` again if required): `try {... /* do something else */ } catch (Exception e) { /* If exception is thrown */ throw; }` – Dmitry Bychenko Jan 13 '20 at 10:08
  • As well as the above comments, maybe give this a skim too? https://stackoverflow.com/questions/38497774/catching-exceptions-with-catch-when – mouldycurryness Jan 13 '20 at 10:09
  • please check [try catch exception handling](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch) documentation – oleksa Jan 13 '20 at 10:09
  • 2
    Are you looking for `TryGet` pattern? https://ayoungdeveloper.com/post/2017-03-28-using-the-tryget-pattern-in-csharp/ – Dmitry Bychenko Jan 13 '20 at 10:11

4 Answers4

1

So what you are looking for is a try catch statement. This kind of structure is fairly common across many languages but for C# it's pretty wonderful. I am going to refer you to Microsoft's documentation on the c# error handling. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch

This should teach you everything you need to know. For a simple rundown on how it works in my terminology:

try {
//execute code that you expect to throw an exception
}
Catch (KindOfError ErrorVariable) {
//Error has been thrown, execute code for it.
msgbox.show("Error Raised: " + ErrorVariable.Code.ToString())
}
Finally {
//Execute code here you want to run regardless of error outcome
msgbox.show("This code runs with or without an exception being thrown")
}

This should help you out!

Marc
  • 19
  • 3
1

You can take advantage of delegates and create some static helper.

You can use Action or Func in that case. Add another extension method which accepts Func if you need to return some value from executed function.

public static class SilentRunner
{
    public static void Run(Action action, Action<Exception> onErrorHandler)
    {
        try
        {
            action();
        }
        catch (Exception e)
        {
            onErrorHandler(e);
        }
    }

    public static T Run<T>(Func<T> func, Action<Exception> onErrorHandler)
    {
        try
        {
            return func();
        }
        catch (Exception e)
        {
            onErrorHandler(e);
        }

        return default(T);
    }
}

And then use it so:

SilentRunner.Run(
     () => DoSomething(someObject),
     ex => DoSomethingElse(someObject, ex));

In case of Func, you can take result as well:

var result = SilentRunner.Run(
     () => DoSomething(someObject),
     ex => DoSomethingElse(someObject, ex));
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
0

Use just a normal try-catch block. If the exception is thrown, it will go to the catch block, if not, it will continue executing the lines after the method that might throw an exception.

try
 {
 MethodThatMightThrowException()
 // do something else
 }
catch
 {
 // do something
 }
SomeBody
  • 7,515
  • 2
  • 17
  • 33
0

Technically can catch the exception:

 try { 
   var result = DoSomeAction(arguments);

   /* do something else : result is a valid value*/
 }
 catch (SomeException) {   //TODO: put the right exception type
   /* If exception is thrown; result is not valid */ 

   // throw; // uncomment, if you want to rethrow the exception
 }

However, you can implement TryGet pattern and have a clear if:

https://ayoungdeveloper.com/post/2017-03-28-using-the-tryget-pattern-in-csharp/

And use it as

 if (TryDoSomeAction(arguments, out var result)) {
   /* do something else : result is a valid value*/
 }
 else {
   /* result is not valid; if "exception" is thrown */ 
 }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215