Handling Exceptions [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am working in a code-base(C# 3.5), which is littered with exception handling blocks which return true/false, when inside in a function which returns 'bool'.
catch (Exception ex) { return false; }
This is not correct practice.I am thinking of logging the exception, and have a local variable(to function) which will be initialized.And, this variable will be returned at the end of function.
What do you think?

The usual accepted way to handle exception is to handle them only if you can do something about it. You can of course handle a generic exception just for log puroposes but you should reraise it once you're done.
Your application logic shouldn't rely on exceptions. If there is absolutely no other way to do it, then at least handle concrete exceptions instead of the generic one...

Personally, I would get rid of all of these catch blocks and let the exception bubble up when it happens.
As you say, using exceptions for application logic is bad practice.
Have a catchall exception handler that will catch all such exceptions and log them and terminate the program (if that's the right thing for this program).

It is highly subjective what you want here.
It is old C-style code to have your functions return a true/false value depending on the function succeding or not. In the C# world, it is alot more common to throw exceptions.
You can debate for a long time which is the right path to choose for your code base.
My general point of view is to stick to the exceptions, they have the advantage that they bubble up and usually require less code. And there is also great support for actually logging uncaught exceptions.

You inherited code where the original programmer just didn't want to deal with errors. As written, the program will simply malfunction (say, not save a record to the database) and there's no way to find out why it malfunctioned. Especially since this is dbase code, this will cause random data corruption and loss of precious data.
You indeed cannot leave the code the way it is. The very first thing you need to do is remove all try/catch statements so the program terminates when there's an error. Add an AppDomain.UnhandledException event handler to log the exception so you know what went wrong. Fix errors you'll encounter by correcting code or validating the data. Do expect this to take time, it is very likely that you'll discover many design problems that were shoved under a doormat before.

That's certainly better than what you've got!

Although I wouldn't recommend using the bool return value as proper exception handling, if there is already a lot of code written that way, going and making sweeping modifications everywhere may not be the best idea.

Throwing an exception is generally better than returning false - an exception can at least give the receiver some clue of what happened and why the failure occurred.
The return value of a method should be the result of a method, or it should throw an exception explaining why the requested operation could not be completed.

Related

Is it a bad idea return a tuple instead of throw an exception? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have a method, that always has to return an object of type MyType. If it returns null it is because I don't have the needed information to return a value.
So I was thinking that a posibility it is to throw an argument exception if I don't have the needed information.
Another solution, it is to return a tuple, first item null or the object as result. The second item a string, null if I can return the value or a string with the reason why it is null.
I was consideration this second option, because I guess it is more versatile, who calls this method, if get a null, can know the reason of why it is null and don't need to handle the exception, that requieres more code. Also, if it is called in the UI layer, it can tell the user what information it is needed.
An exception it is more expensive if it is thrown, and also, from a point of view, I considerate the exception the way to handle something that I can't control in another way, but in this case I can know in advance if I have the needed information or not from the user, so it is not something unexpected like if I try to load a file and the file doesn't exist, for example, or try to connect to a network resource and the network is down.
Also, argument exception it is a generic exception, if I want to show to a user a understanding message but also I want a more detailed message for the developer, it is more complex code.
So I was wondering if really it is a bad idea to return a tuple or it is better to throw an exception.
I think a touple can be very usefull, because it can return the value of the method, but also can provide aditional information in another items.
This is a variant on the Return codes vs exception discussion.
I would recommend using a specialized type rather than just a plain tuple. This should either have a value, or a string/error code. This should force the caller to handle at least one case, for example by having OnSuccess(Action<T>) and OnFail(Action<string) methods. See Result of T for an example
If this is preferable to exceptions somewhat depend on if failure is expected or not. I think it is appropriate for something like a Parse-method. For reading a file I would prefer exceptions since reading the file can fail at any time for many possible reasons. I.e. a result object fits best with a functional style.

Catching generic non-fatal exceptions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Conventional wisdom suggests we should only catch the specific exception types we're expecting:
try
{
int.Parse(str); //I am aware of TryParse(), this is just for the sake of example
}
catch (FormatException ex)
{
Console.WriteLine (ex);
}
catch (OverflowException ex)
{
Console.WriteLine (ex);
}
However, sometimes we don't really care which exception happened (as long as it's not fatal), maybe because we just want to let the user know an error occurred. In these cases we can do something like this:
try
{
Foo();
}
catch (Exception ex)
{
if (IsCriticalException(ex))
{
Environment.FailFast("System Error", ex);
}
Console.WriteLine ("Error running Foo: {0}", ex);
}
Where IsCriticalException can be implemented similarly to System.ClientUtils.IsCriticalException. I am generally in favor of this approach for a couple of reasons:
Some methods can throw many exception types and it can be cumbersome to catch them all. For example, File.Open can throw nine different types of exceptions.
Some methods can throw undocumented exceptions. This is either due to lacking documentation, or due to some bug. For example, ICommunicationObject.Close can actually throw ArgumentException due to an obscure bug. Some methods cannot even know statically which exceptions could be thrown by them, since they load other modules / plugins dynamically. Supposedly they could wrap all such "external" exceptions with their own known exceptions, but I believe not all of them do.
The critics of this approach argue that a method's exceptions are part of its contract. If an exception is thrown that is not part of this contract, we should assume its state is corrupt. We will have also discovered a bug in the method (one we otherwise would not have spotted since we'd have swallowed the unexpected exception). We could then relay this bug to the framework's developers, and this is a win - especially if those developers are in our company, so we've "helped ourselves" so to speak.
I admit, the critics present valid points, but I feel they are a bit idealistic. Practically, I think generic non-fatal exception catching makes sense in a lot of situations. Am I making sense?
Related reading:
How to Design Exception Hierarchies
Vexing exceptions
Conventional wisdom suggests we should only catch the specific exception types we're expecting
Actually, I think you should catch exactly those exceptions, that you can handle. There is no use in catching exceptions just to rethrow them and it does not make sense to let those exceptions pass that you would have had a cure for.
In your above example, I think having a catch-all block would have been fine, after all not converting that string is a recoverable error, no matter what exception pops up (except for OutOfMemoryException, which cannot be handled anyway because any attempt at handling would use memory).

Throwing an exception or returning an error - What is the better approach? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
What is the better approach when handling errors - throwing it as an exception or returning a an object that contains the error and its details?
I'm thinking what is the better approach to notifying errors - in terms of system resources, coding practices and overall enterprise practices ?
I've seen in most cases, the sample code throws a custom exception containing the error information. But I was thinking if it was better to just return an object instantiated from a class (for example: class DatabaseError)?
I believe throwing exceptions in C# can be resource intensive and this would involve having (possibly) a lot of try-catch blocks.
Thanks!
Exceptions are generally considered to be the preferred mechanism for relaying error conditions up the application chain to where they can be dealt with and managed in such a way that they do not cause the application to fail completely and terminate.
However, it is also generally considered poor practice to use the exception-handling mechanism as a logic path - that is, to make the catching of an error condition a prerequisite for later correct or alternative functionality (e.g. to attempt to open a file which may or may not exist, catch the exception if it does not exist, and present a file-browser dialog as a consequence - in this example, the 'NOT FOUND' error condition should be detected before attempting to open the file rather than regarding the exception path as the route by which the user is asked to locate it).
DO NOT return error codes.
Exceptions are the primary means of reporting errors in frameworks.
-Framework Design Guidelines
See that excellent book for details and for ways to deal with performance.
When the caller is expecting that a condition may occur, it is best to inform the caller of that condition via return code. When a condition occurs which the caller is not expecting, it is best to inform the caller via an exception.
Because most languages do not provide any means for a called routine to 'magically' know what the caller is expecting, the only way a routine will know what the caller is expecting is for the caller to tell it. There are a few patterns I would suggest:
Have both a "DoSomething" method and a "TryDoSomething" method. The former will throw an exception if it cannot achieve the intended objective, while the latter will throw an exception.
Use a single method with a Boolean or enumeration parameter which indicates whether a routine should behave as a "Try" or "Do" method. This is often useful in conjunction with small "DoSomething" and "TryDoSomething" methods which call the combined routine passing an appropriate parameter value. Although many implementations would make the combined routine protected, having it public may allow it to be called from another "Do or Try" routine, passing the ThrowOnFailure value from the other routine to the inner routine.
Have a single method with overloads that include or do not include a 'ref' parameter that will be used to indicate success or failure. The version of the function with the parameter will use it to indicate failure (without throwing an exception), while the overload without it will throw an exception in the failure case.
Have a single method with a delegate which should be invoked in case of failure. Conceptually, this is an even better approach than passing a Boolean parameter, since the delegate can not only throw an exception the invoking code will be prepared to catch; it can also set flags or take other action so when the invoking code catches the exception, it can be sure what really happened. Unfortunately, figuring out the optimal form for the delegate, including what parameters it should take, is tricky.
Approach #1 seems to be Microsoft's recommended pattern, though I think #2 can help avoid duplicate coding. Approach #3 would be similar to a convention used in Borland Pascal some years back, that worked out relatively intuitively. Approach #4 would seem the nicest, but I haven't figured out how best to do it practically.

What is better: int.TryParse or try { int.Parse() } catch [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I know.. I know... Performance is not the main concern here, but just for curiosity, what is better?
bool parsed = int.TryParse(string, out num);
if (parsed)
...
OR
try {
int.Parse(string);
}
catch () {
do something...
}
Better is highly subjective. For instance, I personally prefer int.TryParse, since I most often don't care why the parsing fails, if it fails. However, int.Parse can (according to the documentation) throw three different exceptions:
the input is null
the input is not in a valid format
the input contains a number that produces an overflow
If you care about why it fails, then int.Parse is clearly the better choice.
As always, context is king.
Is it exceptional for the conversion to sometimes fail, or is it expected and normal that the conversion will sometimes fail? If the former, use an exception. If the latter, avoid exceptions. Exceptions are called "exceptions" for a reason; you should only use them to handle exceptional circumstances.
If it is indeed expected that the conversion will sometimes fail, I like to use int.TryParse and such neatly on one line with the conditional (Ternary) operator, like this:
int myInt = int.TryParse(myString, out myInt) ? myInt : 0;
In this case zero will be used as a default value if the TryParse method fails.
Also really useful for nullable types, which will overwrite any default value with null if the conversion fails.
The first. The second is considered coding by exception.
Personally, I'd prefer:
if (int.TryParse(string, out num))
{
...
}
The first! You should not code by exception.
you could shorten it to
if (int.TryParse(string, out num))
First, by far. As George said, second is coding by exception and has major performance impacts. And performance should be a concern, always.
Catching an Exception has more overhead, so I'll go for TryParse.
Plus, TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.
That last part copy-pasted from here
Something else to keep in mind is that exceptions are logged (optionally) in the Visual Studio debug/output window. Even when the performance overhead of exceptions might be insignificant, writing a line of text for each exception when debugging can slow things right down. More noteworthy exceptions might be drowned amongst all the noise of failed integer parsing operations, too.

C#: Article about throwing proper type of exception [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Sometimes I dont know witch type of exception should I throw. So I usually throw Exception(). Is there some nice article about this?
The problem with throwing a generic exception is that it restricts the ability of your code further up the stack to handle it properly (i.e. best practice is to trap the most specific exception possible before falling back, and to only capture what you can handle).
Jeffrey Richter has an excellent section on exception handling (including info on the System.Exception namespace) in CLR via C#
"Framework Design Guidelines" by Cwalina and Abrahms covers this topic really well (IMHO).
It is available for free online here, or the book (not free) here (UK) or here(US). Look in the section entitled Design Guidelines for Exceptions.
If you are not making any attempt to recover from an error, you can just throw an Exception with a string to tell you what went wrong. (Or if you will perform the same action regardless of what error occurred).
Other than making it obvious to a programmer what went wrong by using a new exception name rather than putting it in the Message, and exception can contain data to help you recover from a particular exception.
For example, an ArgumentNullException has a property ParamName, which you should set when you throw the exception. When the caller catches it, he can then look up this property and decide to pass a new value for the argument which caused the error, or can print a relevant error to inform the programmer what went wrong.
It's unfortunate that exceptions are rarely used to their full potential (in many open source APIs and such), and are often simply inserted to inform a programmer what went wrong. There's not much difference between these 2 if you don't plan to read the ParamName property when you catch it. (Many people will not bother, and only catch an Exception anyway).
throw new ArgumentNullException("arg1");
throw new Exception("arg1 is null");
It can be difficult to recover from an error fully, but in some applications though, you might find it desirable to create custom exceptions which can provide all the details you need.
For now, I would just put Exception into the Object browser search in VS, and see what is there already. Their names are pretty self explanatory, so you should be able to pick out something suitable.
Well, the one thing you shouldn't do is throw Exception itself.
Always look for an appropriate subclass.
I don't know of any publication spelling out which exception to throw when, but ArgumentException and InvalidOperationException should take care of most of your cases.
Ask separate questions about separate cases if they come up.
I would suggest dividing exceptions into a few categories based upon the system state:
The method failed in such a fashion that it did nothing; the state of any underlying data was not disturbed, and is probably valid. Typical scenarios: trying to retrieve from a collection an object which isn't there, or add one which already is. Another possible scenario: a communications timeout in cases where it should not have caused any data loss (and were retrying the operation might succeed if the problem was simply that the other end was simply too slow).
The method failed in a fashion which may have disturbed the underlying data structure, or the underlying data structure may have been corrupted previously. Further operations should not be attempted with this data structure unless steps are taken to validate it. Another possible scenario: a communications timeout occurs when a record has been partially retrieved, and the partially-retrieved data is now lost. Depending upon the protocol, it may be necessary to perform some recovery action on the connection, or to close it and initiate a new one.
Something is seriously wrong with the system state, and recovery is likely not possible.
Unfortunately, existing .net exceptions don't fit anything like that pattern; it would have been nice if there were a type ExceptionBase from which things like ThreadAbortException, CpuHasCaughtFireException, and the 'normal' Exception were derived, and all 'normal' exceptions were derived from Exception. I understand that .net 4.0 somewhat kludges in such a design, but I don't know the exact mechanics. In any case, I would suggest that any user-defined exceptions should be divided into groups as above, with all exceptions in each group sharing a common ancestor distinct from other groups.
There's an article by Krzysztof Cwalina ("a Principal Architect on the .NET Framework team at Microsoft") called Choosing the Right Type of Exception to Throw that sheds some light on this. It deals with choosing the right exception to throw and guidance on creating custom exceptions.

Categories