This question already has answers here:
Why catch and rethrow an exception in C#?
(17 answers)
Closed 8 years ago.
If I want to preserve the stack trace and I have this catch block...
try
{
//Cause exception here...
}
catch (CustomException customEx)
{
//Handle custom exception here...
}
catch
{
throw;
}
Will the above catch (without parameter) rethrow the exception?
Your question is unclear. Your actual question seems to be "Does a catch(SpecificException) fall through to the general catch?", to which the answer is "no".
If by "the" exception you mean "any other exception than CustomException", then yes, they will be rethrown.
If you want to rethrow the latter too, you'll also need a throw in the catch(CustomException customex).
you can use try-catch-finally
A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.
For more information and examples on re-throwing exceptions, see try-catch and Throwing Exceptions. For more information about the finally block, see try-finally.
for more details see
https://msdn.microsoft.com/en-us/library/dszsf989.aspx
Related
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.
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 7 years ago.
Improve this question
One of my co-worker asked what exception would I get if you execute a query that has a wrong table name. I was not able to answer since I always catch exceptions like the code below,
try
{
ExecuteQuery();
}
catch(Exception ex)
{
//show an error message
}
so I do not know what kind of error will be raised until it actually happens. But I like to code in this way because I can simply copy and paste that catch block at anywhere that needs to be try and catch blocked.
My question is that is it important to know what exceptions will be thrown and try to make as many specific catch exceptions as possible?
My question is that is it important to know what exceptions will be
thrown and try to make as many specific catch exceptions as possible?
It depends. If you are going to catch and handle specific exception then it makes sense to catch specific exception first and then the base exception.
One example could be to determine insertion of duplicate primary key, where you want the user to enter different value since the table can't allow insertion of duplicate key. In that case you will catch SqlException first and then have another block of Exception to catch any other.
try
{
ExecuteQuery();
}
catch (SqlException sqlException)
{
if (sqlException.Number == 2627) //duplicate key
{
// ask user to enter new value, repeat `ExecuteQuery`
}
}
catch (Exception ex)
{
//show an error message
}
Without catching SqlException you will not have access to Number field which has details about the particular SqlException.
(by the way, the above code is just an example to catch and handle specific exception, insertion of duplicate key can be avoided by checking the value first in table).
It depends. But generally, it is good to catch specific exceptions if you wish your application to behave differently under different circumstances. For example, a FileNotFoundException could tell you that your user needs to verify a path. General catch blocks are useful at the highest level of your application, but getting more specific further down the line allows you better control over how to respond to specific problems.
It is important if you want to show some personalized message about the exception to the user. For example: if it is a NullException, it shows a message with some code, for example 5504. And this number he/she says to helpdesk to inform about the problem. An article about this is here
This question already has answers here:
What kind of Exceptions cannot be handled? [duplicate]
(2 answers)
Closed 8 years ago.
So from http://msdn.microsoft.com/en-us/library/ms173161.aspx
Once an exception is thrown, it propagates up the call stack until a catch statement for the exception is found.
So the implcation is that all exception typess can be either caught by a catch(ExceptionType) or a generic catch.
However this is plainly not true. For example AccessViolationException bypasses standard exception handling
How to handle AccessViolationException
So what other exceptions also bypass standard exception handling?
I would say that a StackOverflowException is most likely unhandled, I'm not aware of others.
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).
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;