This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
the difference between try/catch/throw and try/catch(e)/throw e
Pardon my stupidity, anyone knows difference between them?
try
{
return 1 / 0;
}
catch (Exception)
{
throw;
}
try
{
return 1 / 0;
}
catch
{
throw;
}
try
{
return 1 / 0;
}
catch (Exception e)
{
throw(e);
}
Will catch and rethrow only exceptions derived from Exception.
Will catch and rethrow any exception. (Edit: Since CLRv2, all exceptions are derived from Exception so this is identical to 1. See Eric Lippert's comment below).
Will catch any exception derived from Exception and throw it again, thus resetting the stack trace of the exception.
A catch clause without arguments can catch any type of exception. This is sometimes referred to as the "general" catch clause. You should probably never use this in a production application, but I suppose it might sometimes be useful for debugging. It looks like this:
catch
{
}
A catch clause can also specify the particular exception class that you want to catch. You should always do this in your applications because you're only supposed to catch exceptions that you know how to handle. For example, you might want to catch a DivideByZeroException; you'd do it like this:
catch (DivideByZeroException)
{
}
Of course, that has the side effect that you're unable to refer to the exception class itself inside of the catch block because you haven't assigned it to a variable. If you need to call properties or methods on the instance of the exception class that you catch, you'll need to include a named variable in the catch statement. That is probably what you're most used to seeing, and it looks like this:
catch (DivideByZeroException ex)
{
// do something with ex here
}
Then there are two ways to write the throw() statement, and it matters which one you choose:
The first just looks like this:
throw;
It is written without any arguments, and the purpose is to rethrow the caught exception while preserving the stack trace and as much information about the original exception as possible.
(There are still some edge cases where this can cause you to lose the stack trace, but generally this is much preferred over the alternative below.)
The second option passes an instance of an exception class as an argument, and looks like this:
throw(ex);
or this:
throw ex;
This also rethrows the specified exception, but as mentioned above, it has the downside of losing some of the stack trace information that tells you what method was responsible for throwing the exception. It's rare that you'll use this except to throw a new exception object that you create in the same method.
For example, if you wanted to catch a low-level exception and wrap it within a new exception object for consumption by a higher-level function, you would use this form.
The first two are equivalent.
The third one should generally be avoided: it rethrows the exception from its own stack frame, losing information about the original frames in the process.
catch (Exception) - Catches anything that derives from Exception class
catch (Exception e) - Catches anything that derives from Exception class and assign it to the variable e, which you can use.
catch - catches anything thrown.
There is no difference between example 1 and 2. Both rethrows the original exception, and both catches the general Exception. You would use example 1 if you wanted to catch a more specific exception, such as DivisionByZeroException.
For the last example, you are not re-throwing the exception; but throwing the same exception object that you caught. This causes the exception stacktrace to be re-set to the location where you throw it - which might be a problem because the stacktrace then does not point to the location in code, where the error actually occured.
The difference is that throw e; will throw an exception with a different stack trace. See this accepted answer.
Related
Is there a difference when catching exceptions not of a type between :
try
{
...
}
catch (TaskCanceledException)
{
throw;
}
catch (Exception exception)
{
...
}
and :
try
{
...
}
catch (Exception exception) when (!(exception is TaskCanceledException))
{
...
}
Yes, there is.
In the second block of code you are filtering on general exception type. It is not meant to be filtered, what happens if "TaskCanceledException" is thrown? you are not handling it and it will escalate to enclosing code. You are not really meant to filter anything on "Exception" type since it is the parent for all other type of exception and it is the last point of handling exception. A better option would be to create a custom exception and put them in separate block of catch and filter on them if needed.
The first option is more correct compared to the second one. Though you should not be throwing any exception and stay away from them, unless it is a complete deal breaker. On top of that what is the point of putting a catch block with Exception type bellow TaskCanceledException catch block which throws exception? You are basically telling that "I Would like to handle all exception" when using catch with Exception type, but at the same time you through one exception in exceptional case. Either throw the original exception or handle them.
Hope this makes sense.
Refer to this link Stackoverflow
Catch blocks already allow you to filter on the type of the exception:
catch (SomeSpecificExceptionType e) {...}
The when clause allows you to extend this filter to generic expressions.
Thus, you use the when clause for cases where the type of the exception is not distinct enough to determine whether the exception should be handled here or not.
The Dixin's Blog explained the difference with code example and VS screenshots.
Exception filter does not unwind the stack, and catch block does unwind. When executing catch block, this catch block’s method becomes the top frame of the stack. As a result, all the methods called by current method are removed from the stack. In contrast, exception filter can be helpful for runtime debugging. For example, if above Catch method is executed:
In my processing I would like to log any error along with the user and code details and proceed on with my work.
I am currently using a try catch block which includes a generic catch, but is catching a generic exception is a bad thing? Such as the exception could be a stackoverflowexception or outofmemoryexception and need to be handled differently.. .
But I am not sure how to avoid catching these fatal exceptions. I am looking for suggestions.
Why I want to catch all exceptions
Because I don't want a failure in one form's processing to affect the others in the loop.
Why I am catching specific exceptions:
I understand I can look for stackoverflowexception, outofmemoryexception etc... but my point is, there could be many of them...looking for each and every would make my code lengthy. I am not sure if that is the best process.
But I am not sure how to avoid catching these fatal exceptions
Well, 2 things.
First, you can always rethrow them, for example, after logging.
Second, you can catch every exception you want and if you do not catch System.Exception then all you do not catch will bubble up - that is C# 101 for beginners, so if you have a problem with that, back to reading the documentation about exceptions in general.
Exceptions cascade down. If you want to handle certain exceptions differently, implement a different catch block.
try
{
ThisMethodMayThrowException();
}
catch(StackOverflowException ex)
{
//handle a StackOverFlowException
}
catch(OutOfMemoryException ex)
{
//handle a OutOfMemoryException
}
catch(Exception ex)
{
//handle all other types.
}
In general though, you should only plan to handle expected exceptions. For example, if you're writing to a file that you expect to exist, you might anticipate a FileNotFoundException. If you tried to handle every possible exception, your code would become quite long and unwieldy, to little benefit.
Microsoft provides excellent info on exception handling.
Reverse your thinking... because the advice catching generic exception is being misinterpreted.
Handle all exceptions which are known explicitly (do the log and continue processing), but always have a generic catch all exception handler to stop all processing and handle that unknown.
In your example an overflow exception could comprise data or let malicious actors take over the system in unexpected ways; hence continuing on, should not be done.
If you know all the exceptions you want to catch, you write a catch block for each specifically:
try
{
}
catch (IOException)
{
}
catch (InvalidCastException)
{
}
...
Then all the ones you don't want to catch (and thus allow to potentially take down your program) will keep bubbling up.
I am currently using a try catch block which includes a generic catch,
but I have heard from many people that catching generic exception is a
bad thing(as the exception could be a stackoverflowexception or
outofmemoryexception).
You should know which Exception types your method calls might throw.
It could be discovered either at the Method documentation, example:
/// <exception cref="DivideByZeroException">Why it's thrown.</exception>
public void MethodThatMightThrowDivideByZeroException(){...}
or by looking at the Method code, example:
throw new DivideByZeroException();
That way, you would be able to catch it easily:
try
{
ThisMethodMayThrowException();
}
catch(DivideByZeroException ex)
{
//handle a DivideByZeroException
}
I want the code calling a function to handle any exception raised in the function. If I write:
try
{
// Code than may raise an exception
}
catch
{
throw;
}
The exception will be passed back with the callstack. Could I write the following instead and get the same result? Is there any reason to use the try catch in this case?
// Code that may raise an exception
In the scenario you've presented, the only reason to catch, and then rethrow, the exception, is if you're doing something else in the catch block, like logging or cleanup. Otherwise, it's entirely a no-op.
Good on you that you're using throw, rather than throw e, by the way, if you do need this construct. The former preserves the callstack; the latter does not.
There is no reason to use try/catch in that case.
If you were logging any information or encapsulating the exception in a higher-level one, then the try/catch would be indicated.
I'm just trying to understand this a little better.
I understand there are many different exception types, and according to some reading I've done, all exception types are caught by Exception. First of all, can I be assured that this is true?
try{
...
}
catch(Exception x){
//No matter what fails in the try block, x
//will always have a value since all exception
//types are caught under Exception? I guess
//What I really want to know, is will this ever
//Fail?
}
catch(SystemException x){
//This code will never execute since all
//exceptions are caught in the first catch?
}
Next, how does this catching hierarchy work? If Exception is at the top, is every other exception type one level under Exception, or are there multiple type tiers, like if Exception is the parent of ExceptionSomething, which is the parent of ExceptionSomethingElse?
addendum:
Or if we have code like this:
try{
...
}
catch(SystemException x){
//If there is an exception that is not a SystemException
//code in this block will not run, right (since this is
//looking specifically for SystemExceptions)?
}
It actually depends on your .NET version and configuration. In C++/CLI you can throw anything; it doesnt have to be an Exception. In 1.1 (IIRC) ou could only catch these with a catch block like:
catch {...}
Which isn't very helpful - you can't see what happened. In 2.0 (IIRC) by default such exceptions are automatically wrapped up inside a dummy RuntimeWrappedException subclass. However, for compatibility you can turn this off. I beg you: don't :)
Yes, this works because all standard exceptions inherit from Exception.
Your code will work but you'll need to put the handler for Exception after all specialized exception types. (The first matching handler will execute.)
Exceptions that do not inherit from Exception would not be caught because they are not the specified type. But the .NET exception classes all inherit from this base class.
Some people don't think it's a good idea but I generally only catch Exception, unless I want special handling for a particular exception type.
Yes, Exception is inherited from the Object class, and all exceptions are inherited from the Exception class.
The above link will show you the hierarchy of all the exceptions.
System.Object
System.Exception
Microsoft.Build.BuildEngine.InternalLoggerException
Microsoft.Build.BuildEngine.InvalidProjectFileException
Microsoft.Build.BuildEngine.InvalidToolsetDefinitionException
Microsoft.Build.BuildEngine.RemoteErrorException
...
Some of these exception, like the SystemException you mentioned have further exceptions inherited from them, but they all still inherit from the Exception class:
System.Object
System.Exception
System.SystemException
Microsoft.SqlServer.Server.InvalidUdtException
System.AccessViolationException
System.Activities.ValidationException
System.AppDomainUnloadedException
System.ArgumentException
System.ArithmeticException
...
To answer the second part of your question, an example of an exception hierarchy from the .Net Framework:
ArgumentNullException inherits from
ArgumentException inherits from
SystemException inherits from
Exception
You should try to handle the most specific case that you can.
try{
//something
}
catch(ArgumentNullException ex){
//handle ArgumentNullException
}
catch(SystemException ex1)
{
//handle other kinds of SystemException
if(IDontWantToHandleThisExceptionHere(ex1))
{
throw;// not throw new Exception(ex1);
}
}
The latter, exceptions can inherit from the base Exception class or any other class that inherits the base class.
For example: SqlException inherits from DbException which inherits from ExternalException which inherits from SystemException which finally inherits from Exception.
Yes, all exception types are inherited from exception.
And, the way inheritance works, you can have multiple level of inheritance
MyAppException : Exception {
}
MyAppFileNotFoundException : MyAppException {
}
This is usually used to have different behavior with different types of exceptions
try {
openfile('thisFileDoesNotExist.txt');
}
catch (MyAppFileNotFoundException ex)
{
//warn the user the file does not exist
}
catch (Exception ex)
{
//warn the user an unknown error occurred, log the error, etc
}
I use asp.net 4, c# and ef4.
I would like to know what is the best way to catch an generic Exception from Entity Framework.
At the moment I use Exception it is appropriate?
How catch a more specific one?
Thanks for your time.
try
{
context.DeleteObject(myLockedContent);
context.SaveChanges();
}
catch (Exception)
{
e.Cancel = true;
}
It's rarely good to catch generic exceptions and just cancel them. Exceptions are there to help you ensure you code can act appropriately.
You can catch specific exception types just as you have for the generic (albeit with the identifier you have missed on your example) thus:
catch (OptimisticConcurrencyException ex)
{
// Do some real work to resolve the exception
}
The exception type specified in the catch statement tells the runtime to catch that specific and any child exceptions. As a result you need to organise your catch statements from the most specific exception to the least, i.e. :
catch (OptimisticConcurrencyException ex)
{
// Do some real work to resolve the specific exception
}
...
catch (Exception ex)
{
// Do some real work to resolve the generic 'catch-all' exception
}
Do not do that.
You are hiding errors which could severely affect the reliability of your application. An exception is thrown for a reason, just continuing on like nothing have happened is just wrong.
You're method cannot return the result as promised, which will affect all code that use it. But the calling methods will not know about the exception and will in worst case continue as nothing have happened and therefore produce undesired results.
You should only use catch all
a) when wanting to wrap exceptions at layer boundaries (but do include the original exception).
b) when the exception have propagated to the top layer (which would terminate your application if the exception is not caught).
Other than that, only catch exceptions when you can handle them. That means that you, by catching the exception, can return the result that the caller expects.
the way you are catching in your example is bad, always log the exception somewhere and somehow, for example on a text file or to an SMTPAppender, you can use Log4Net and get it running in very short time with minimal coding from your side.
Said so, it really depends if you want to handle different exceptions differently, for example if a file was not found you can decide to create it or to tell the user to do something, if the more general exception is thrown you may act differently...
just keep in mind you should put all your catch clauses from the more specific to the more generic one, in your example, if you have multiple catches, the one you wrote should be put in the end.