C# try catch continue execution
c#, try-catch
Solution
Leaving the catch block empty should do the trick. This is almost always a bad idea, though. On one hand, there's a performance penalty, and on the other (and this is more important), you always want to know when there's an error.
I would guess that the "callee" function failing, in your case, is actually not necessarily an "error," so to speak. That is, it is expected for it to fail sometimes. If this is the case, there is almost always a better way to handle it than using exceptions.
There are, if you'll pardon the pun, exceptions to the "rule", though. For example, if function2 were to call a web service whose results aren't really necessary for your page, this kind of pattern might be ok. Although, in almost 100% of cases, you should at least be logging it somewhere. In this scenario I'd log it in a `finally` block and report whether or not the service returned. Remember that data like that which may not be valuable to you now can become valuable later!
Last edit (probably):
In a comment I suggested you put the try/catch inside function2. Just thought I would elaborate. Function2 would look like this:
public Something? function2()
{
try
{
//all of your function goes here
return anActualObjectOfTypeSomething;
}
catch(Exception ex)
{
//logging goes here
return null;
}
}
That way, since you use a nullable return type, returning null doesn't hurt you.
Problem
I have a question that might seem fairly simple (of course if you know the answer). A certain function I have calls another function but I want to continue execution from the caller even though the callee has thrown an exception. Let me give you an example: ``` something function1() { try { //some code int idNumber = function2(); //other code that need to execute even if function2 fails return something; } catch(Exception e) {//... perhaps something here} } ``` EDIT: function1 also has a return statement so nothing can in fact crash on the way In function2 I need to do stuff but I only need to log if anything fails, example: ``` int function2() { try { //dostuff } catch(Exception e) { //Log stuff to db } } ``` ok, now my question is, what should I do if I wanted to continue execution in function1 even if function 2 throws an error? Sometimes I mix up if I should do throw; or throw e; or throw nothing at all (leave catch block empty)