I have an application that connect with two server. If it cannot connect with a server, an exception is thrown. I want the program to continue executing and instead try to connect to the other server. How can I do that?
Asked
Active
Viewed 1,605 times
-8
-
8`try{//...}catch(Exception ex){//...}` – Tim Schmelter Aug 28 '14 at 12:51
-
Why all the down votes? Granted this question is a very basic question about how `C#` works, but does it not have value for absolute beginners? – Philip Pittle Aug 28 '14 at 12:58
-
@beto13 - Recommend reading Rob Milles free C# Yellow Book for a good introduction to C#, with topics including Exception Handling: http://www.robmiles.com/c-yellow-book/ – Philip Pittle Aug 28 '14 at 12:59
-
1@PhilipPittle - If you hover over the downvote icon it states that "this question does not show research effort" (for the record I didn't downvote this question but I have downvoted numerous similar questions) – Sayse Aug 28 '14 at 13:00
-
@Sayse - I get the research argument. Just not sure how an absolute beginner would show research effort in a basic language construct. For example: http://stackoverflow.com/q/121162/1224069. Maybe the downote hovertext has changed over the years. – Philip Pittle Aug 28 '14 at 13:03
-
1@PhilipPittle - I don't want to spam this post any more but when I type into google "C# How to keep running a program if an exception occurs?" (the op's question title with c# prefixed); the top results are a stack overflow question, a tutorial on exception handling, and then 6 msdn links all about handling exceptions – Sayse Aug 28 '14 at 13:05
-
@PhilipPittle Yes, questions like that exist, but that was 6 years ago. The rules of what's allowable on SO and the standards of a good question have changed dramatically since then ], not to mention that this question has been asked many times before. – tnw Aug 28 '14 at 13:29
-
Dang, wrong link. A better duplicate: http://stackoverflow.com/questions/14973642/how-using-try-catch-for-exception-handling-is-best-practice – jgauffin Aug 28 '14 at 14:15
2 Answers
1
Use a try catch block.
var serversToTry = new []{"Server1", "Server2"};
foreach (var server in serversToTry)
{
try{
//connect to server
return; //if you made it this far, connection succedded.
}
catch (Exception e)
{
//log e if you want
}
}

Philip Pittle
- 11,821
- 8
- 59
- 123
1
Just use the go to function try-catch
:
try
{
//do something
}
catch(SpecificException ex)
{
}
catch(LessspecificException ex)
{
}
catch(EvenLessSpecificException ex)
{
}
catch(Exception ex)
{
//general exception
}
finally
{
//execute always!
}
Note, that you can use multiple catch
statements to catch different exceptions. Use the most specific exceptions first and generalize from there on.
the finally
statement is optional, but if you implement it, it will get called everytime, no matter if an exception occured or not.

Marco
- 22,856
- 9
- 75
- 124