简体   繁体   中英

c# if-else within catch statement

I'm trying to write a single if-else block within a catch method, but when I get the error that 'not all code paths return type int.'

Essentially, I'm writing a method that saves a UserName and Password to a Sql CE database, and I want to test for one specific error. (UserName already exists.) The UserName column is unique, so it will reliably throw a SqlCeException with NativeError = 25016. I want to display that with an error message, otherwise handle other exceptions in a more generic way.

My code is:

  try
  {
    //insert command  (This is where the duplicate column error is thrown)
    //Select @@Identity & Return it
  }
  catch (SqlCeException ex)
  {
   if (ex.NativeError == 25016)
        MessageBox.Show("Username already in use."); 
   else
     //whatever
  }

I've tried showing a different, more generic message and get the no return error. I've tried throwing a new exception and catching it in another block. Same error. I've tried returning -1 (as a sort of flag value). Same error.

There doesn't appear to be a more specific error than SqlCeException for this specific case (Though I ma have just failed me debug-fu).

Any creative work-arounds? Worst case, I'll write a method that checks the DB for duplicate usernames before calling this method.

It looks like your method returns an int . You need to return a value of type int from your catch block.

  try
  {
    //insert command  (This is where the duplicate column error is thrown)
    //Select @@Identity & Return it
  }
  catch (SqlCeException ex)
  {
   if (ex.NativeError == 25016)
        MessageBox.Show("Username already in use."); 
   else
   {
     //whatever  
   }
   return -1;
  }

Sounds like your function returns an int value.

In your try block you get and return an integer value. That's fine.

In the catch block you do not mention returning an integer. This is the problem.

So when the function takes the exception path, it doesn't have an integer to pass back causing the error.

Your whole function need to return value. Since you are eating exception in try-cathc you need to have return of some sort at the end of the function.

Use finally block to return int:

 try
  {
    //insert command  (This is where the duplicate column error is thrown)
    //Select @@Identity & Return it       
  }
  catch (SqlCeException ex)
  {
   if (ex.NativeError == 25016)
        MessageBox.Show("Username already in use."); 
   else
     //whatever
  }
  finally
  {
    return -1;
  }

If try block return Identity value then finally return -1 will not effect. Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM