Search code examples
c#try-catchfault

c# fault instantly crashes program


//interface
[OperationContract]
[FaultContract(typeof(UserManagementFault))]
void AddUser(User user);

//class implements interface
public void AddUser(User user)
{
    //throw faultException (instant crash)
    throw new FaultException<UserManagementFault>(new UserManagementFault("User exists"),
        new FaultReason("User exists"));
}

//fault
[DataContract]
public class UserManagementFault
{
    private string _message;

    public UserManagementFault(string message)
    {
        _message = message;
    }

    [DataMember]
    public string Message { get { return _message; } set { _message = value; } }
}


//method invoker
try {
    AddUser();
} catch(FaultException<UserManagementFault>) {
    
}

When the throw new FaultException line executes the program crashes, but I want the program to jump into the catch part at the bottom of the code. What am I doing wrong?

EDIT: I noticed that Visual Studio was pausing the program, but when I pressed Continue the program got into the catch block... Strange


Solution

  • Looks like something wrong in your code for custom exceptions. i would add a general exception too to see whats going on

    try {
        AddUser();
    } catch(FaultException<UserManagementFault>) {
    
    }
    catch(Exception ex) {
    
    }