Return value for exception

Why is this code not compiling?
This gives me an error:

not all code paths return a value

Code:

public bool isUserProfileHashed(string username) { bool isHashed = false; MembershipUser u = null; u = Membership.GetUser(username); if (u != null) { try { u.GetPassword(); } catch (Exception exception) { // An exception is thrown when the GetPassword method is called for a user with a hashed password isHashed = true; return isHashed; } return isHashed; } 
+4
source share
7 answers

You forgot to put return out from if, put it after the end is over

 public bool isUserProfileHashed(string username) { bool isHashed = false; MembershipUser u = null; u = Membership.GetUser(username); if (u != null) { try { u.GetPassword(); } catch { // An exception is thrown when the GetPassword method is called for a user with a hashed password isHashed = true; } } return isHashed; } 

[change]
Delete Unnecessary Return (@Fredrik Mรถrk)
A fixed exception that was not used also deleted it.

+10
source

There is no return statement outside the if block. Sometimes, if the block may not execute.

+1
source

No return if u is null.

+1
source

If u == null, your entire if statement will be passed through . Outside the if statement, there is no return statement.

That's why you see: not all code paths return a value .

Just add a return statement after the if block:

 public bool isUserProfileHashed(string username) { bool isHashed = false; MembershipUser u = null; u = Membership.GetUser(username); if (u != null) { // ... return isHashed; } // more code here if you need it return ??? ; // <--- **ADD THIS** } 
+1
source

You do not handle the case where u == null and return a value if this condition is met.

+1
source

If u turns out to be null , you will not return!

This should work better.

 public bool isUserProfileHashed(string username) { bool isHashed = false; MembershipUser u = null; u = Membership.GetUser(username); if (u != null) { try { u.GetPassword(); } catch (Exception exception) { // An exception is thrown when the GetPassword method is called for a user with a hashed password isHashed = true; return isHashed; } return isHashed; } else { //Throw or return false, whatever throw new Exception("Could not get user ..."); } } 
+1
source

The amendment to your method was marked by other posters, however, is it possible to replace the whole method with this line?

 if(Membership.Provider.PasswordFormat == MembershipPasswordFormat.Hashed) 
+1
source

All Articles