How to correctly let an exception to bubble up?
If I use Try-Catch when calling a method, is just throwing an exception inside a method like not trying to catch it at all?
For illustration: Are these approaches do the same work?
Example 1:
try
{
MyFileHandlingMethod();
}
catch (IOException ex)
{
string recfilepath = "...
string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString();
File.AppendAllText(recfilepath, rectoadd);
}
catch (exception)
{
throw;
}
...
MyFileHandlingMethod()
{
...
TextReader tr2 = new StreamReader(nfilepath);
resultN = tr2.ReadLine();
tr2.Close();
...
}
Example 2:
try
{
MyFileHandlingMethod();
}
catch (IOException ex)
{
string recfilepath = "...
string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString();
File.AppendAllText(recfilepath, rectoadd);
}
catch (exception)
{
throw;
}
...
MyFileHandlingMethod()
{
...
try
{
TextReader tr2 = new StreamReader(nfilepath);
resultN = tr2.ReadLine();
tr2.Close();
}
catch (Exception)
{
throw;
}
...
}
Yes, those 2 approaches have almost the same effect; rethrowing will unwind the stack of the exception - meaning the stack frames "below" the method where the throw; will be discarded. They'll still be in the stack trace, but you won't be able to access their local variables in the debugger unless you break on thrown exceptions.
A catch/throw block like the one below where you don't do anything with the exception (like logging), is useless:
catch (Exception)
{
throw;
}
Remove it to clean up, in both your samples. In general, avoid entering a catch block if possible
And your method has another exception related problem, it does not free resources properly. The tr2.Close(); belongs in a finally clause but it's much easier to let the compiler handle that with a using() {} block :
void MyFileHandlingMethod()
{
...
using (TextReader tr2 = new StreamReader(nfilepath))
{
resultN = tr2.ReadLine();
} //tr2.Dispose() inserted automatically here
...
}
First of all you should use the using block with resources as this will take care of closing your resources correctly. The second example is pretty much useless as you don't do any work in the exception handler. Either you should remove it, or wrap it in another Exception to add some information.
Yes, the result is the same.
However, both will result in an unclosed stream if there is an error while reading it. You should use a using block or a try ... finally to make sure that the stream is closed:
using (TextReader tr2 = new StreamReader(nfilepath)) {
resultN = tr2.ReadLine();
}
Note that there is no Close in this code. The using block will dispose the StreamReader, which will close the stream.
The using block is compiled into a try ... finally which it uses to make sure that the StreamReader is always disposed, but the exception will bubble up to the calling method.
I suggest you use your first example, with these changes:
try
{
MyFileHandlingMethod();
}
catch (IOException ex)
{
string recfilepath = "...";
string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ex.Message.ToString();
File.AppendAllText(recfilepath, rectoadd);
throw; // rethrow the same exception.
}
// no need for second catch}
You probably want to rethrow the exception once you have logged it, because you are not doing any actual recovery from the error.
Related
I'm trying to figure out the "best" way execute a (close) statement in my sql data access layer methods.
I was wondering which of the two ways is considered more correct (thanks):
Option #1
public void dbOperation( ... )
{
try
{
_cmd.Open();
_cmd.Execute();
}
catch (Exception ex)
{
throw ex;
}
finally
{
_cmd.Close()
}
}
Option #2
public void dbOperation( ... )
{
try
{
_cmd.Open();
_cmd.Execute();
}
catch (Exception ex)
{
_cmd.Close()
throw ex;
}
_cmd.Close();
}
Neither is correct. You shouldn't have a catch clause just to re-throw the exception again, clearing out its stack trace, and doing nothing productive, which is what your first option does.
You should just be closing in the finally:
try
{
_cmd.Open();
_cmd.Execute();
}
finally
{
_cmd.Close()
}
Your second snippet has the same problem with it, since you're improperly re-throwing the exception.
The best option would be to use a using, which is just a syntactic sugar for a try/finally without a catch:
using(var command = ...)
{
command.Open();
command.Execute();
}
This has the added benefit of also ensuring that the scope of the command is exactly the same as when it's valid to use it. A try/finally block requires the command to be a valid identifier after it has been disposed of.
Option #1 is the only correct one of the two. In fact, you can get the equivalent of option #1 using less code:
try
{
_cmd.Open();
_cmd.Execute();
}
finally
{
_cmd.Close()
}
If an exception is thrown, there's no need to have a catch block to just re-throw it. If you want to do something in the catch block, such as logging the exception, be sure to do this:
try
{
_cmd.Open();
_cmd.Execute();
}
catch (Exception ex)
{
logException(ex);
throw; //Just say throw, not throw ex, to preserve the original stack trace
}
finally
{
_cmd.Close()
}
Option #1. If you use option2 you won't execute cmd.close unless it throws an exception
I know, we can use try-catch block to handle exceptions. But I have some doubts in the usage of Try-Catch.
What is the difference between
try
{
//Some code
}
catch
{
}
and
try
{
//Some code
}
catch(Exception)
{
}
and
try
{
//Some code
}
catch(Exception oops)
{
}
In my program, I need to catch all exceptions and I don't want to log them. From the above mentioned Try-Catch blocks, which should be used?
Using a catch without a parameter is no longer useful as of framework 2.0, as all unmanaged exceptions are wrapped in a managed exception. Before that you could use it to catch exceptions thrown by unmanaged code.
You can specify just the type of the exception if you don't want to use any information from it, but usually you would want a name for it so that you can get to the information:
try {
// some code
} catch(Exception) {
// i don't care about any information in the Exception object, just the type
}
vs.
try {
// some code
} catch(Exception ex) {
// use some information from the exception:
MessageBox.Show("Internal error", ex.Message);
}
You should always try to have an exception type that is as specific as possible, as that makes it easier to handle the exception. Then you can add less specific types to handle other exceptions. Example:
try {
// some database code
} catch(SqlException ex) {
// something in the database call went wrong
} catch(Exception ex) {
// something else went wrong
}
So far you use catch (Exception), the first and the second are the same. You catch everything in this case. When you like to catch a specific exception like UnauthorizedAccessException, you have to use the second one like this:
try
{
//Some code
}
catch (UnauthorizedAccessException)
{
MessageBox.Show(oops.Message);
}
In the third case you can use the Exception through the variable oops.
For example:
try
{
//Some code
}
catch (Exception oops)
{
MessageBox.Show(oops.Message);
}
Or with a specific exception:
try
{
//Some code
}
catch (UnauthorizedAccessException oops)
{
MessageBox.Show(oops.Message);
}
Generic try catch, this will catch any type of exception
try
{
//Some code
}
catch
{
}
This will catch the specific type of exception that you specify, you can specify multiple.
try
{
}
catch (UnauthorizedAccessException)
{
}
This will do the same as above but give you a variable that has access to the properties of an exception.
try
{
}
catch (UnauthorizedAccessException ex)
{
}
You should be using the last one, and handling in a clean way your exception.
The first too way are the same but are "Eating Exceptions", witch is the worst thing to do.
At least log your exception!
Your first and second example are the same. They will both catch any exception, without any information about the exception. The third exception stores the exception in oops, which you can then use to get more information about the exception.
Look at msdn documentation: http://msdn.microsoft.com/en-us/library/vstudio/0yd65esw.aspx
The best is specify which kind of errors you would like catch.
The third one is the best...
You can catch any kind of specific exception and it will be precise... This helps in identifying the exact exception and easy for us to correct them as well
For eg: one can catch DivisionByZeroException, TargetInvocationException, ArrayOutOfBoundException, etc...
They are all pretty much the same (I assume the first is shorthand for writing the 2nd), the difference with the last is you are putting the exception object into a variable so you can use it in the catch.
Usually when I see code like this I tend to worry as it's generally not a good idea as you could be masking bigger problems with your application.
Rule of thumb - handle what you can, let everything else bubble up.
i think it has the same function - To trace where the error is set/ or where did something get wrong,
using try-catch this way
> try {
//some codes
}
catch
{
//anything
//e.g.:
MessageBox.Show("Something is wrong!");
}
this tells the that there is something wrong but didn't show the detailed report. (Clever way to hide some errors is don't put anything in the catch{} xD, but this is not advised to do)
the next is to show detailed report of the error
try
{
//some codes
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
hope this helps! :D
//I have written code in Catch Block
try {
} catch(Excepetion ex) {
// I have written code here If Exception Occurs then how to handle it.
}
You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed.
try
{
}
catch(Excepetion ex)
{
try
{
}
catch
{
}
//or simply throw;
}
finally
{
// some other mandatory task
}
Finally block may not get executed in certain exceptions. You may see Constrained Execution Regions for more reliable mechanism.
The best way is to develop your own exceptions for different Layers of application and throw it with inner exception. It will be handled at the next layer of your application. If you think, that you can get a new Exception in the catch block, just re throw this exception without handling.
Let's imagine that you have two layers: Business Logic Layer (BLL) and Data Access Layer (DAL) and in a catch block of DAL you have an exception.
DAL:
try
{
}
catch(Excepetion ex)
{
// if you don't know how should you handle this exception
// you should throw your own exception and include ex like inner exception.
throw new MyDALException(ex);
}
BLL:
try
{
// trying to use DAL
}
catch(MyDALException ex)
{
// handling
}
catch(Exception ex)
{
throw new MyBLLException(ex);
}
try
{
// Some code here
}
catch (Exception ex)
{
try
{
// Some more code
}
catch (Exception ex)
{
}
}
For the lines of code that could throw an exception in catch block make extra explicit try..ctach block. Besides consider having finally block, to have lines to run by all means there. The same question may raise for the finally block. So if your code is likely to throw some exception in the finally block, you could also add try..catch there.
try
{
}
catch (Exception ex)
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
finally
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
Double-faulting often happens in well-designed 3g programming languages. Since protected mode and the 286, the general design for hardware languages is to reset the chip on a triple fault.
You are probably ok designing your way out of a double fault. Don't feel bad about having to do something to stop processing / report an error to the user in this case. If you run into a case where, eg., you catch an IO exception (reading/writing data) and then try to close the stream you're reading from, and that also fails, its not a bad pattern to fail dramatically and warn the user that something truly exceptional happened.
A catch block isn't special in any particular way. You will have to either use another try/catch block or not handle the error.
My friend Atul.. if you if write try..catch in catch block, and if again exception occurs in inner try..catch, same problem will raise again.
So address this issue you can handle those errors in application level events in Global.asax
check below links..
http://msdn.microsoft.com/en-us/library/24395wz3%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/fwzzh56s%28v=vs.80%29.aspx
let me know if this works for you.. :)
Let us say we have an external server which we use (e.g.-telephony station, etc.). Also we have the next code:
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
throw;
}
Theoretically UpdateCallState could throw but we would hide this exception using that code and would treat only exceptions generated by CreateCall in a right way.
The question is, what is the right pattern for these situations so that we treat all the exceptions correctly?
You can always nest another try..catch inside the first catch and deal with it appropriately.
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
try
{
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch(Exception updateEx)
{
// do something here, don't just swallow the exception
}
throw; // this still rethrows the original exception
}
Break it up. Something like
if !TryCreateExternalCall(callParams)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
else
{
throw new ExternalServiceException(???);
}
TryCreateExternalCall should of course log the exception and stacktrace, before it swallows and returns false.
It is not a good practice to throw exception in Catch block.
The try, Catch suggest that
try
{
//make some changes. If something goes wrong go to Catch.
}
Catch(exception)
{
//I will clean the mess. Rollback the changes.
}
Catch the exception, only if you can handle the exception. Else bubble it up let the caller decide on what to do with the exception.
You should catch the most specific exception first, followed by the most general exceptions.
try
{
externalService.CreateCall(callParams);
}
catch (CreateCallExceptionType ccEx)
{
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch (Exception ex)
{
//do something
}
And then you could handle the UpdateCallState exception within the method.
I know how to use try-catch-finally. However I do not get the advance of using finally as I always can place the code after the try-catch block.
Is there any clear example?
It's almost always used for cleanup, usually implicitly via a using statement:
FileStream stream = new FileStream(...);
try
{
// Read some stuff
}
finally
{
stream.Dispose();
}
Now this is not equivalent to
FileStream stream = new FileStream(...);
// Read some stuff
stream.Dispose();
because the "read some stuff" code could throw an exception or possibly return - and however it completes, we want to dispose of the stream.
So finally blocks are usually for resource cleanup of some kind. However, in C# they're usually implicit via a using statement:
using (FileStream stream = new FileStream(...))
{
// Read some stuff
} // Dispose called automatically
finally blocks are much more common in Java than in C#, precisely because of the using statement. I very rarely write my own finally blocks in C#.
You need a finally because you should not always have a catch:
void M()
{
var fs = new FileStream(...);
try
{
fs.Write(...);
}
finally
{
fs.Close();
}
}
The above method does not catch errors from using fs, leaving them to the caller. But it should always close the stream.
Note that this kind of code would normally use a using() {} block but that is just shorthand for a try/finally. To be complete:
using(var fs = new FileStream(...))
{
fs.Write(...);
} // invisible finally here
try
{
DoSomethingImportant();
}
finally
{
ItIsRidiculouslyImportantThatThisRuns();
}
When you have a finally block, the code therein is guaranteed to run upon exit of the try. If you place code outside of the try/catch, that is not the case. A more common example is the one utilized with disposable resources when you use the using statement.
using (StreamReader reader = new StreamReader(filename))
{
}
expands to
StreamReader reader = null;
try
{
reader = new StreamReader(filename);
// do work
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
This ensures that all unmanaged resources get disposed and released, even in the case of an exception during the try.
*Note that there are situations when control does not exit the try, and the finally would not actually run. As an easy example, PowerFailureException.
Update: This is actually not a great answer. On the other hand, maybe it is a good answer because it illustrates a perfect example of finally succeeding where a developer (i.e., me) might fail to ensure cleanup properly. In the below code, consider the scenario where an exception other than SpecificException is thrown. Then the first example will still perform cleanup, while the second will not, even though the developer may think "I caught the exception and handled it, so surely the subsequent code will run."
Everybody's giving reasons to use try/finally without a catch. It can still make sense to do so with a catch, even if you're throwing an exception. Consider the case* where you want to return a value.
try
{
DoSomethingTricky();
return true;
}
catch (SpecificException ex)
{
LogException(ex);
return false;
}
finally
{
DoImportantCleanup();
}
The alternative to the above without a finally is (in my opinion) somewhat less readable:
bool success;
try
{
DoSomethingTricky();
success = true;
}
catch (SpecificException ex)
{
LogException(ex);
success = false;
}
DoImportantCleanup();
return success;
*I do think a better example of try/catch/finally is when the exception is re-thrown (using throw, not throw ex—but that's another topic) in the catch block, and so the finally is necessary as without it code after the try/catch would not run. This is typically accomplished with a using statement on an IDisposable resource, but that's not always the case. Sometimes the cleanup is not specifically a Dispose call (or is more than just a Dispose call).
The code put in the finally block is executed even when:
there are return statements in the try or catch block
OR
the catch block rethrows the exception
Example:
public int Foo()
{
try
{
MethodThatCausesException();
}
catch
{
return 0;
}
// this will NOT be executed
ReleaseResources();
}
public int Bar()
{
try
{
MethodThatCausesException();
}
catch
{
return 0;
}
finally
{
// this will be executed
ReleaseResources();
}
}
you don't necessarily use it with exceptions. You may have try/finally to execute some clean up before every return in the block.
The finally block always is executed irrespective of error obtained or not. It is generally used for cleaning up purposes.
For your question, the general use of Catch is to throw the error back to caller, in such cases the code is finally still executes.
The finally block will always be executed even if the exception is re-thrown in the catch block.
If an exception occurs (or is rethrown) in the catch-block, the code after the catch won't be executed - in contrast, code inside a finally will still be executed.
In addition, code inside a finally is even executed when the method is exited using return.
Finally is especially handy when dealing with external resources like files which need to be closed:
Stream file;
try
{
file = File.Open(/**/);
//...
if (someCondition)
return;
//...
}
catch (Exception ex)
{
//Notify the user
}
finally
{
if (file != null)
file.Close();
}
Note however, that in this example you could also use using:
using (Stream file = File.Open(/**/))
{
//Code
}
For example, during the process you may disable WinForm...
try
{
this.Enabled = false;
// some process
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.Enabled = true;
}
I am not sure how it is done in c#, but in Delphi, you will find "finally" very often. The keyword is manual memory management.
MyObject := TMyObject.Create(); //Constructor
try
//do something
finally
MyObject.Free();
end;