开发者

What is the best way to use C# try/catch/finally to behave like if/else?

开发者 https://www.devze.com 2023-03-23 11:47 出处:网络
I am trying to set up try/catch/finally to behave like if/else. I am not sure of the most elegant way to do this simple thing.

I am trying to set up try/catch/finally to behave like if/else. I am not sure of the most elegant way to do this simple thing.

public开发者_Python百科 bool login()
{
bool isLoggedIn = false;
if (connectToServer(Path,username,password) ) // if successful
  {
     isLoggedIn = true;
  }
  else
  {

  }

return isLoggedIn;
}

Here is what I attempted with Exceptions.

public bool login()
{
 bool isLoggedIn = false;

 try{
    connectToServer(Path,username,password)
    isLoggedIn = true; 
  }
  catch(myConnectionException ex)
  {


  }

return isLoggedIn;
}

the 2nd line "isLoggedIn" is going to get executed although the previous line raises an exception upon failure. My thinking is to ask "if an exception was thrown, I don't want that line to be executed. Can I (should I) access the exception object at this point to test? (or is it out of scope?) I am a former C coder so I am trying to "keep it c#" to do a simple thing. I just want to perfect my skills and be in line with "best practices". Thanks DTM


No it won't get executed. However, this is bad practice as there is a costly context-switch to handle the exception. You should only use exceptions in exceptional cases.

I would consider combining the two approaches.


What would be wrong with doing something like this?

bool isLoggedIn = false;

try
{
    isLoggedIn = connectToServer(Path, username, password);
}
catch (ExceptionType1 ex1)
{
    //Recover from this exception type.
}
catch (ExceptionType2 ex2)
{
    //Recover from this exception type.
}

Exceptions aren't a "replacement" for if statements. They're for handling error conditions, if one should occur, and using them to control the flow of an application is certainly not advisable. At the very least they're slow, and using them to control flow may hide actual real errors from you when you may actually want the application to fail.

EDIT: As @Anthony Pegram mentions in the comment below, dealing with all exception types in a single catch block is bad practice (something I'm guilty of all too often), since it also hides exceptions from you that you might actually want to handle specifically.


connectToServer should throw a myConnectionException if it wasn't successful


I would highly recommend moving the try/catch block to connectToServer. You should never control program flow with exceptions, as mentioned the context switch is horrible overhead.

Have connectToServer always return true or false (have it internally catch it's errors and return false). and simply:

return connectToServer(Path,username,password);


In this simple example the

isLoggedIn = true;

is not reached if an exception is thrown so it is still false (as initialized) if the connection call throws an exception. Even if it is not a catched exception type the part of setting isLoggin to true will never be reached.

As mentioned before: Don't use exception instead of if/then/else or switch/case. If your code has more method calls after setting the isLoggedIn to true then you should reset this to false because in the catch because this will be the returned result.

By the way, there is no difference in the rule of using exceptions in c# or i c++. This seems common to both languages.


This will work, but should not be done. Your best bet would be to code it as :

public bool login()
{
    return connectToServer(Path,username,password);
}

Short and sweet. Exceptions are very bad to use except in exceptional cases. Of course, if you want to pick up the connectToServer exceptions then you can use something like:

public bool login()
{
    try
    {
        return connectToServer(Path,username,password);
    }
    catch(exception ex)//or the specific exception you are after
    {
        return false;
    }
}

meaning that the exceptional occasion of the failure will be picked up by the exception, but most of the time the exception will not be called.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号