Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Exception handling in frameworks

I have to write a FTP (AUTH TSL) framework in C#. I'm a noob at writing frameworks.
E.g. when I prove that a file exists and it doesn't, what should I do?

  • Throwing a Exception for the programmer that uses the framwork?
  • Printing a ExceptionMessage (Console.WriteLine()) without throwing a Exception?

What is professional in this case?

like image 821
Luca Nate Mahler Avatar asked Dec 08 '25 13:12

Luca Nate Mahler


2 Answers

Broad question actually, but there are some clues to get you on the way:

  1. Never use Console.WriteLine() or any stuff like that in a framework.
  2. For methods like Framework.FileExists, if file doesn't exist, simply return false value. That's the true nature of the Boolean return value. That's more semantic.
  3. For operations that encounter problems, throw a custom, or predefined exception. For example, if you need an argument and you want to get sure that no null has been passed to your method, then simply check the argument in your method's body and if it's null, throw ArgumentNullException.
like image 152
Saeed Neamati Avatar answered Dec 10 '25 01:12

Saeed Neamati


To pass an "error code" back as return value, it is common to use enums. Your upload method could return

public enum UploadResult
{
    Success,
    PasswordInvalid,
    UserInvalid,
    FileNotFound,
    HostNotFound
}

The user of your framework then can easily use it like this:

if (Ftp.Upload(User, Pass, Host, File) != UploadResult.Success)
{
    MessageBox.Show("Sorry, something went terribly wrong.");
}

or check for more specific reasons and try again.

Edit: And as written in my comment to your original posting: If something really unexpected happens or the user input is clearly invalid, throw an exception.

like image 31
linac Avatar answered Dec 10 '25 01:12

linac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!