Throwing a New Exception Best Practice [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is the following good practice and if not what should be done?
catch(Exception e)
{
throw new Exception(e.Message, e);
}

No, this is not good practice if you're throwing another exception of the exact same type with the same message. In doing this, you complicate the stack trace and make debugging more of a pain.
If you're going to throw a new exception, it should differ from the original in some significant way. It should be another type, for example, or in some other way (like a more specific error message) clarify the reason for the exception. If you can't do either of those things, then simply rethrow the current exception using throw;.
Or, even better, don't catch it at all. Rethrowing actually messes up the stack trace a tiny bit as well (the current frame's error location is set to the rethrow point rather than the spot where the exception happened), so if you don't have anything you personally have to do to handle the exception, then hands off -- just let it propagate and let the caller handle it.

Just rethrow the exception that was caught, no need to create a new one.
catch(Exception e)
{
// Do some logging...
throw;
}
Some reading on rethrowing exceptions and implications on the stack trace for it: http://msdn.microsoft.com/en-us/library/ms182363(v=vs.100).aspx

It depends on what you are trying to do. That exact code would be pointless, but something like
catch(Exception ex)
{
throw new ApplicationSpecificException("Error while doing something specific: " + contextualData, ex);
}
will help tremendously while debugging.

If you need do something with the exception before re-throwing it, do this:
catch(Exception e)
{
// Additional handling here
throw;
}
Throw by itself simply re-throws the current exception. If you don't need to handle it here, don't catch it in the first place.
Also, in your example you are catching any type of exception but throwing in its place a generic Exception - probably not very useful.

If the code really is just:
try
{
// something
}
catch(Exception e)
{
throw new Exception(e.Message, e);
}
Just delete the try/catch, it's not doing anything productive. Exchanging throw; for the throw new... is better, but still not productive.
if there's something else going on in the catch, do as Gromer details, and just use throw;

Related

Why Don't we Use General Exception Class (Exception) for Catching All Types Of Exceptions [duplicate]

This question already has answers here:
Is it really that bad to catch a general exception?
(15 answers)
Closed 4 years ago.
Why do we use the more specific exceptions like IndexOutOfRangeException
and DivideByZero exceptions when we can catch them in a catch block like this:
try
{
//Some Work
}
catch(Exception E){}
You should only ever write specific code to handle exceptions that you reasonably expect to be thrown. If you understand that specific code could throw a specific type of exception then you can determine exactly what to do in that situation. If you catch absolutely any type of exception then you will have no idea what the cause was and thus you can't know what should be done about it.

Best practice exception handling [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 6 years ago.
Improve this question
Comming from here, I'm not sure about exception handling. MSDN shows the frist way. Is the second one also ok? It's shorter and should produce the same output.
Question: Can I use the second way without any side effects?
try
{
string s = null;
ProcessString(s);
}
catch (ArgumentNullException e)
{
LogError(e.Message);
}
catch (Exception e)
{
LogError("Error");
}
or
try
{
string s = null;
ProcessString(s);
}
catch (Exception e)
{
LogError((e is ArgumentNullException) ? e.Message : "Error");
}
First of all, logging "Error" string when you have unknown exception is very bad practice. You should log error details - message, inner exception(s) etc. That's why logging frameworks provide methods which accept Exception object which would be logged.
Next, you should catch separate types of exception only if you handle them differently. In your case there is simple error logging in both cases, so you don't need to distinguish ArgumentNullException from other exceptions:
try
{
ProcessString(null);
}
catch (Exception e)
{
LogError("Failed to process string", e);
}
And last - don't write your own logging framework - take a look on NLog, log4net etc.
Also note that usually you should handle only high-level exceptions. E.g. if you have ArgumentNullException or IndexOutOfRangeException when you are trying to do some business operation, it's not good to show these low-level exceptions to user. You usually wrap them in custom high-level exception (e.g. DataMigrationException) and handle them later
The answer really is "it depends".
It's not that bad, but more specific exceptions are better. When you're more specific, it means that you actually understand, more concretely, what your application is trying to do as well as have more control over it. You should really just handle the exceptions you expect, and treat everything else as a bug.
If you're specifically catching the exceptions that you know a code block or method can throw, then there's a higher likelihood you can actually recover instead of just logging and hoping for the best.

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).

What does C# throw and finally means in lay men terms? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Say you are running a program,
and it meets a "THROW" statement... what happens?
Will the program stop? Will it continue?
And what's "FINALLY" for?
Please I appreciate an explanation in simple words
if program meeets throw instruction it will throw an exception.
Will your application stop or continue running depends on will you handle that exception ot not with catch instruction.
finally, instead, is introduced to guarantee the execution of the containing code inside that block either exception was thrown or not.
See the MSDN documentation for throw here: http://msdn.microsoft.com/en-us/library/1ah5wsex.aspx
In brief, throw raises an exception. If you are in a try-catch block then it will be caught, if not your program may crash.
The finally block executes after the try-catch block regardless of whether there was an exception which was thrown (and caught).
The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution. Usually the throw statement is used with try-catch or try-finally statements. When an exception is thrown, the program looks for the catch statement that handles this exception.
The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.
Throw: http://msdn.microsoft.com/en-us/library/1ah5wsex(v=vs.80).aspx
Finally: http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx
You find a lot of information here:
http://msdn.microsoft.com/en-us/library/ms173160(v=vs.80).aspx
Exceptions have the following properties:
When your application encounters an exceptional circumstance, such as a division by zero or low memory warning, an exception is generated.
Use a try block around the statements that might throw exceptions.
Once an exception occurs within the try block, the flow of control immediately jumps to an associated exception handler, if one is present.
If no exception handler for a given exception is present, the program stops executing with an error message.
If a catch block defines an exception variable, you can use it to get more information on the type of exception that occurred.
Actions that may result in an exception are executed with the try keyword.
An exception handler is a block of code that is executed when an exception occurs. In C#, the catch keyword is used to define an exception handler.
Exceptions can be explicitly generated by a program using the throw keyword.
Exception objects contain detailed information about the error, including the state of the call stack and a text description of the error.
Code in a finally block is executed even if an exception is thrown, thus allowing a program to release resources.

C# why throw errors [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Im not getting the throw keyword, why use it? What are the benefits of it?
As of now I've got this in my UI class:
try
{
Classreference.MethodToRun();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This works but I guess with throw I could make the method I am calling throw the error instead and catch it in my UI class? But why? What is better about it? Is it done to make the classes more object oriented or what? I am guessing if I just catch the error in my UI class I wont need to change the code if I change the method I am calling, but instead change the error message in the method being changed?
You use throw to indicate that an error has occured or to pass an existing error on to a higher level.
You use catch when you want to handle the error (Exception).
Throwing the exception is an improvement over the older procedural way of handling errors where you would return error codes.
The reason it is better is because you can write your logic for the simple success case, and when things go wrong you simply throw an exception, no error handling in your lower level code. It is then up to the higher levels of the application to decide what to do when a particular exception is throw.
asawyer is right, you need to google and read up on error handling, it is a wide subject and you only really 'get it' after practice, talking, and reading about it. throw is something you probably won't need to use overly often, but you can occasionally use it to stop unwanted behaviour and create clearer errors for programmers using your methods. I know it is quite contrived but take this example:
public string WriteToFile(FileStream fs) {
if (fs == null) {
throw new ApplicationException("you passed a null filestream");
}
// write to file
}
You could just attempt to write the FileStream to a file without validating it, but in doing so you create a more understandable error for anyone consuming your method.
You can use the throw keyword to throw an exception to the higher method.
Using this way, you can ocassionally make a better use of the exception, like closing database-access or something like that.
What you are doing here is effectively masking a lot of information that you could get from the exception.
what you regularly want to do is catch the exception, log the relevant information to some place where you can review it (logfile, db, eventlog) and then either throw(), which will keep you stack trace intact, or throw another "user friendly" exception which is masking the technical implementation.

Categories