Is it okay to have a try-catch in an object’s constructor?
MyObject InstanceOfMyObject = new MyObject(9999); // the caller
class MyObject
{
private byte[] A;
public MyObject(ushort Size)
{
try
{
A = new byte[Size]; // might throw an error
}
catch
{
// what do I do here?
// How do I delete this non-initialized object?
// What will be returned to the caller?
}
}
}
Use a factory method and move the try/catch there.
class Foo {
public void Bar() {
var bla = MyObject.TryCreate(9999);
// now need to handle the case where 'bla' is null!
}
}
class MyObject {
public static MyObject TryCreate(ushort size) {
MyObject obj;
try {
// it is a good practice to keep content of try clause as narrow
// as possible to not accidentially catch more than what's intended
obj = new MyObject(size);
} catch (OutOfMemoryException) { // only catch specific types of exceptions
// not enough memory
return null;
}
return obj;
}
private byte[] _array;
// private constructor ensures that only TryCreate can be used to create a MyObject
private MyObject(ushort size) {
_array = new byte[size]; // might throw an error
}
}