I have a class which contains a Phone object.
The phone is a virtual phone, and in the constructor to my class, I pass in the IP Address and the port of the virtual phone I wish to connect to.
Inside the constructor, I then run a method called Connect. In the Connect method I instantiate an IPEndPoint object out of the IP Address/Port combo of the phone, I then instantiate a Socket object, and run the Connect method of the Socket object, passing in my IPEndPoint as the parameter.
If the phone server hasn’t been configured properly for a particular phone (not my job) the connection is refused, and a SocketException is thrown. I am trying to catch this exception.
This is a Windows Form application. Within the scope of the Form object, but outside of the scope of any constructors/methods, I have my phone as an uninstantiated private field like so (IPhone is the interface which my phone uses):
private IPhone _phone;
I have a method called SetupPhone, I instantiate my phone object in here, and am trying to catch the exception here:
private void SetupPhone()
{
try
{
_phone = new Phone(AgentDetails.IPAddress, AgentDetails.Port);
}
catch(SocketException ex)
{
Log.LogException("Error mapping phone to port", ex);
ShowBaloonTip("An error occured starting CTI. Please select your name from the list to try again", ToolTipIcon.Error);
ChangeUser();
return;
}
//Subscribe to Phone events here
}
Here’s the constructor for the phone object:
public Phone(string ipAddress, int port, string password = "FooBar")
{
Connect(ipAddress, port, password);
}
Here is the Connect method:
public void Connect(string ipAddress, int port, string password)
{
_phone = new IPEndPoint(IPAddress.Parse(ipAddress), port);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
_socket.Connect(_phone);
//Redacted
}
On a not properly configured phone, my SocketException is thrown as shown below:

Am I not right in thinking that any exceptions thrown by any methods run in an objects constructor should be safely caught by a try/catch block put around the instantiation of that object? Or is this not the case? I want to catch any errors that may occur when instantiating my object, is this not possible?
http://www.blackwasp.co.uk/VSBreakOnException.aspx
Debug Mode Exceptions
Reset All
Configuring Custom Exceptions