Reputation: 27
Say I have
Method1(); // might return error
Method2(); // should only be executed if previous line successful
I could use try
and catch
, however I still want errors to happen, I just don't want Method2()
to be run if any errors occurred.
Upvotes: 0
Views: 552
Reputation: 16104
There is a "template" for functions that looks like this:
bool TrySomething( out int returnValue )
which return true if successful and false if not. The returnValue
is only valid if the returned bool is true. So you can use those like this:
if( TrySomething(out int someValue) )
{
Method2( someValue );
}
The various TryParse
methods of different types are examples of that.
Another approach would be if Method1
throws an exception:
Method1();
// If Method1 throws an exception, Method2 will not be executed.
// The control flow will be redirected to the "next" catch block
// that handles the exception type or if none of those exist crash
// the app.
Method2();
So, even if you do not surround this with a try/catch block and Method1
throws, the control flow will not move on to execute Method2
.
If you do use a try/catch block, Method2
will also not be executed:
try
{
Method1(); // throws
Method2(); // won't execute
}
catch(SomeException ex)
{
// Control flow will continue here.
// Handle that exception
}
finally // optional
{
// This will be executed regardless of whether there was an exception or not.
}
For further reading:
Upvotes: 2
Reputation: 107
Make Method1 return false on error. Than you can use it like this:
if(Method1()){Method2();}
Upvotes: 0
Reputation: 93
As suggested by @ProgrammingLlama you should do something like this:
try {
MethodWithErrorOrException();
MethodAfter();
}
catch (Exception) {
// Handling
}
finally {
MethodAlwaysCalled();
}
Naturally MethodWithErrorOrException() should rise Exception.
Alternatively you have to use a return value to the method MethodWithErrorOrException() to understand if everything was successful, but it is not the most elegant solution.
Upvotes: 1