Reputation: 83
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
}
Upvotes: 1
Views: 5925
Reputation: 26645
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));
Upvotes: 1
Reputation: 186708
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 */
}
Upvotes: 0
Reputation: 19
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!
Upvotes: 1
Reputation: 8743
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
}
Upvotes: 0