简体   繁体   中英

Try-Catch exception handling in constructor method

I have a seperate class file which contains a constructor method among other methods and I create an instance of this class within a Windows form. I need to do some exception handling within the constructor method, if the required file doesn't exist then catch it with a FileNotFoundException . My only issue is I have no idea how to pass the results of the exception to the Windows form since I can't pass arguments or return any data from the constructor class.

You're making a conceptual mistake. A constructor has a single purpose in life: to prepare a class instance for its busy lifetime. It can therefore have only 2 possible outcomes:

  • Construction succeeds. The object is usable.
  • Construction fails because construction was aborted by an exception.

If the file you mention is vital for the object to function, you shouldn't catch the exception and just let it slip outside to the instantiator. It wouldn't make sense in that case to 'return some error' and leave the object half-usable. The event handler in your form should catch the exception and communicate it to the user.

If there is a use case in which a usable object may still be returned, you should implement a static method, something like public static MyClass instantiateConditionally(string filename, out bool somethingHappenedAlongTheWay) . This would allow you to return an instance still, and return that something went wrong.

Do you need the object to be successfully constructed even if the exception is thrown?

If you don't then don't handle the exception in the constructor; handle it in the windows form method where you are creating the object.

If you do, then I'd suggest implementing in your object a Boolean property HasErrors that returns true if exception(s) were handled in the constructor. Also implement a method GetErrors() which returns any handled exceptions (conveniently stored in an instance field) or null . This way you can always check in your windows form method if any exception was thrown during the creation of the object and act accordingly.

Do you mean something like this?

public class Form1 : Form
{
    ...


    public void button_Click(...)
    {
        try
        {
            var myclass = new MyClass(@"C:\...some file");
            ...
        }
        catch (FileNotFoundException)
        {
            MessageBox.Show("Can't find the file required");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }   
    }
}
public class MyClass
{
   public MyClass(string path)
   {
       if(string.IsNullOrEmpty(path))
           throw new ArgumentNullException();

       if(!File.Exists(path))
           throw new FileNotFoundException();
       ...
   }
}

Here i create an instance of MyClass when the user clicks on some button.

The class contructor of MyClass throws an exception if no path is given or if the file is not found at the specified path.

I use a try catch to catch any exception thrown and display a messagebox to the user.

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