I need some help on how to use try/catch correctly. In the following example I am using the Google Tasks API, but that's not the important thing.
So here's my current code:
try
{
// try something that could cause an exception
Task result = service.Tasks.Patch(body, listId, taskId).Execute();
}
catch (Google.GoogleApiException ex)
{
// handle exception
Debug.WriteLine("exception");
}
This code tries to do something and I am catching possible exceptions. Now instead of only outputting a message when an error occurs (in the catch block) I also want to output a message when everything is ok. I am not sure though, where to put such a message?
If I put a success message in a finally block, it's always displayed, even if there are errors
If I put a success message after try/catch and maybe finally, it's always displayed, even if there are errors
So, would I put a success message in the try block like this?
try
{
// try something that could cause an exception
Task result = service.Tasks.Patch(body, listId, taskId).Execute();
Debug.WriteLine("task updated successfully"); // <------------------ success message
}
catch (Google.GoogleApiException ex)
{
// handle exception
Debug.WriteLine("exception");
}
My understanding was that try contains only code that can fail and obviously Debug.WriteLine("task updated successfully"); is nothing that can fail, but still included in the try block. Please let me know if my understanding of a try block containing only code that can fail was wrong and if it's normal to include a success message in the try block or what is the best practice for my use case.
No, you don't have to only include code that can fail in the try block. You should also include code that requires that call to succeed. For example, if you need to connect to a database and run some queries you would do it all in the try block.
You might want to include a second catch block to catch other exceptions. Just a random thought.
I'm looking at the article C# - Data Transfer Object on serializable DTOs.
The article includes this piece of code:
public static string SerializeDTO(DTO dto) {
try {
XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
StringWriter sWriter = new StringWriter();
xmlSer.Serialize(sWriter, dto);
return sWriter.ToString();
}
catch(Exception ex) {
throw ex;
}
}
The rest of the article looks sane and reasonable (to a noob), but that try-catch-throw throws a WtfException... Isn't this exactly equivalent to not handling exceptions at all?
Ergo:
public static string SerializeDTO(DTO dto) {
XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
StringWriter sWriter = new StringWriter();
xmlSer.Serialize(sWriter, dto);
return sWriter.ToString();
}
Or am I missing something fundamental about error handling in C#? It's pretty much the same as Java (minus checked exceptions), isn't it? ... That is, they both refined C++.
The Stack Overflow question The difference between re-throwing parameter-less catch and not doing anything? seems to support my contention that try-catch-throw is-a no-op.
EDIT:
Just to summarise for anyone who finds this thread in future...
DO NOT
try {
// Do stuff that might throw an exception
}
catch (Exception e) {
throw e; // This destroys the strack trace information!
}
The stack trace information can be crucial to identifying the root cause of the problem!
DO
try {
// Do stuff that might throw an exception
}
catch (SqlException e) {
// Log it
if (e.ErrorCode != NO_ROW_ERROR) { // filter out NoDataFound.
// Do special cleanup, like maybe closing the "dirty" database connection.
throw; // This preserves the stack trace
}
}
catch (IOException e) {
// Log it
throw;
}
catch (Exception e) {
// Log it
throw new DAOException("Excrement occurred", e); // wrapped & chained exceptions (just like java).
}
finally {
// Normal clean goes here (like closing open files).
}
Catch the more specific exceptions before the less specific ones (just like Java).
References:
MSDN - Exception Handling
MSDN - try-catch (C# Reference)
First, the way that the code in the article does it is evil. throw ex will reset the call stack in the exception to the point where this throw statement is losing the information about where the exception actually was created.
Second, if you just catch and re-throw like that, I see no added value. The code example above would be just as good (or, given the throw ex bit, even better) without the try-catch.
However, there are cases where you might want to catch and rethrow an exception. Logging could be one of them:
try
{
// code that may throw exceptions
}
catch(Exception ex)
{
// add error logging here
throw;
}
Don't do this,
try
{
...
}
catch(Exception ex)
{
throw ex;
}
You'll lose the stack trace information...
Either do,
try { ... }
catch { throw; }
OR
try { ... }
catch (Exception ex)
{
throw new Exception("My Custom Error Message", ex);
}
One of the reason you might want to rethrow is if you're handling different exceptions, for
e.g.
try
{
...
}
catch(SQLException sex)
{
//Do Custom Logging
//Don't throw exception - swallow it here
}
catch(OtherException oex)
{
//Do something else
throw new WrappedException("Other Exception occured");
}
catch
{
System.Diagnostics.Debug.WriteLine("Eeep! an error, not to worry, will be handled higher up the call stack");
throw; //Chuck everything else back up the stack
}
C# (before C# 6) doesn't support CIL "filtered exceptions", which VB does, so in C# 1-5 one reason for re-throwing an exception is that you don't have enough information at the time of catch() to determine whether you wanted to actually catch the exception.
For example, in VB you can do
Try
..
Catch Ex As MyException When Ex.ErrorCode = 123
..
End Try
...which would not handle MyExceptions with different ErrorCode values. In C# prior to v6, you would have to catch and re-throw the MyException if the ErrorCode was not 123:
try
{
...
}
catch(MyException ex)
{
if (ex.ErrorCode != 123) throw;
...
}
Since C# 6.0 you can filter just like with VB:
try
{
// Do stuff
}
catch (Exception e) when (e.ErrorCode == 123456) // filter
{
// Handle, other exceptions will be left alone and bubble up
}
My main reason for having code like:
try
{
//Some code
}
catch (Exception e)
{
throw;
}
is so I can have a breakpoint in the catch, that has an instantiated exception object. I do this a lot while developing/debugging. Of course, the compiler gives me a warning on all the unused e's, and ideally they should be removed before a release build.
They are nice during debugging though.
A valid reason for rethrowing exceptions can be that you want to add information to the exception, or perhaps wrap the original exception in one of your own making:
public static string SerializeDTO(DTO dto) {
try {
XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
StringWriter sWriter = new StringWriter();
xmlSer.Serialize(sWriter, dto);
return sWriter.ToString();
}
catch(Exception ex) {
string message =
String.Format("Something went wrong serializing DTO {0}", DTO);
throw new MyLibraryException(message, ex);
}
}
Isn't this exactly equivalent to not
handling exceptions at all?
Not exactly, it isn't the same. It resets the exception's stacktrace.
Though I agree that this probably is a mistake, and thus an example of bad code.
You don't want to throw ex - as this will lose the call stack. See Exception Handling (MSDN).
And yes, the try...catch is doing nothing useful (apart from lose the call stack - so it's actually worse - unless for some reason you didn't want to expose this information).
This can be useful when your programming functions for a library or dll.
This rethrow structure can be used to purposefully reset the call stack so that instead of seeing the exception thrown from an individual function inside the function, you get the exception from the function itself.
I think this is just used so that the thrown exceptions are cleaner and don't go into the "roots" of the library.
A point that people haven't mentioned is that while .NET languages don't really make a proper distinction, the question of whether one should take action when an exception occurs, and whether one will resolve it, are actually distinct questions. There are many cases where one should take action based upon exceptions one has no hope of resolving, and there are some cases where all that is necessary to "resolve" an exception is to unwind the stack to a certain point--no further action required.
Because of the common wisdom that one should only "catch" things one can "handle", a lot of code which should take action when exceptions occur, doesn't. For example, a lot of code will acquire a lock, put the guarded object "temporarily" into a state which violates its invariants, then put it object into a legitimate state, and then release the lock back before anyone else can see the object. If an exception occurs while the object is in a dangerously-invalid state, common practice is to release the lock with the object still in that state. A much better pattern would be to have an exception that occurs while the object is in a "dangerous" condition expressly invalidate the lock so any future attempt to acquire it will immediately fail. Consistent use of such a pattern would greatly improve the safety of so-called "Pokemon" exception handling, which IMHO gets a bad reputation primarily because of code which allows exceptions to percolate up without taking appropriate action first.
In most .NET languages, the only way for code to take action based upon an exception is to catch it (even though it knows it's not going to resolve the exception), perform the action in question and then re-throw). Another possible approach if code doesn't care about what exception is thrown is to use an ok flag with a try/finally block; set the ok flag to false before the block, and to true before the block exits, and before any return that's within the block. Then, within finally, assume that if ok isn't set, an exception must have occurred. Such an approach is semantically better than a catch/throw, but is ugly and is less maintainable than it should be.
While many of the other answers provide good examples of why you might want to catch an rethrow an exception, no one seems to have mentioned a 'finally' scenario.
An example of this is where you have a method in which you set the cursor (for example to a wait cursor), the method has several exit points (e.g. if () return;) and you want to ensure the cursor is reset at the end of the method.
To do this you can wrap all of the code in a try/catch/finally. In the finally set the cursor back to the right cursor. So that you don't bury any valid exceptions, rethrow it in the catch.
try
{
Cursor.Current = Cursors.WaitCursor;
// Test something
if (testResult) return;
// Do something else
}
catch
{
throw;
}
finally
{
Cursor.Current = Cursors.Default;
}
One possible reason to catch-throw is to disable any exception filters deeper up the stack from filtering down (random old link). But of course, if that was the intention, there would be a comment there saying so.
It depends what you are doing in the catch block, and if you are wanting to pass the error on to the calling code or not.
You might say Catch io.FileNotFoundExeption ex and then use an alternative file path or some such, but still throw the error on.
Also doing Throw instead of Throw Ex allows you to keep the full stack trace. Throw ex restarts the stack trace from the throw statement (I hope that makes sense).
In the example in the code you have posted there is, in fact, no point in catching the exception as there is nothing done on the catch it is just re-thown, in fact it does more harm than good as the call stack is lost.
You would, however catch an exception to do some logic (for example closing sql connection of file lock, or just some logging) in the event of an exception the throw it back to the calling code to deal with. This would be more common in a business layer than front end code as you may want the coder implementing your business layer to handle the exception.
To re-iterate though the There is NO point in catching the exception in the example you posted. DON'T do it like that!
Sorry, but many examples as "improved design" still smell horribly or can be extremely misleading. Having try { } catch { log; throw } is just utterly pointless. Exception logging should be done in central place inside the application. exceptions bubble up the stacktrace anyway, why not log them somewhere up and close to the borders of the system?
Caution should be used when you serialize your context (i.e. DTO in one given example) just into the log message. It can easily contain sensitive information one might not want to reach the hands of all the people who can access the log files. And if you don't add any new information to the exception, I really don't see the point of exception wrapping. Good old Java has some point for that, it requires caller to know what kind of exceptions one should expect then calling the code. Since you don't have this in .NET, wrapping doesn't do any good on at least 80% of the cases I've seen.
In addition to what the others have said, see my answer to a related question which shows that catching and rethrowing is not a no-op (it's in VB, but some of the code could be C# invoked from VB).
Most of answers talking about scenario catch-log-rethrow.
Instead of writing it in your code consider to use AOP, in particular Postsharp.Diagnostic.Toolkit with OnExceptionOptions IncludeParameterValue and
IncludeThisArgument
Rethrowing exceptions via throw is useful when you don't have a particular code to handle current exceptions, or in cases when you have a logic to handle specific error cases but want to skip all others.
Example:
string numberText = "";
try
{
Console.Write("Enter an integer: ");
numberText = Console.ReadLine();
var result = int.Parse(numberText);
Console.WriteLine("You entered {0}", result);
}
catch (FormatException)
{
if (numberText.ToLowerInvariant() == "nothing")
{
Console.WriteLine("Please, please don't be lazy and enter a valid number next time.");
}
else
{
throw;
}
}
finally
{
Console.WriteLine("Freed some resources.");
}
Console.ReadKey();
However, there is also another way of doing this, using conditional clauses in catch blocks:
string numberText = "";
try
{
Console.Write("Enter an integer: ");
numberText = Console.ReadLine();
var result = int.Parse(numberText);
Console.WriteLine("You entered {0}", result);
}
catch (FormatException) when (numberText.ToLowerInvariant() == "nothing")
{
Console.WriteLine("Please, please don't be lazy and enter a valid number next time.");
}
finally
{
Console.WriteLine("Freed some resources.");
}
Console.ReadKey();
This mechanism is more efficient than re-throwing an exception because
of the .NET runtime doesn’t have to rebuild the exception object
before re-throwing it.
I'm developing an app and in some parts there are unhandled exceptions. I want to catch them in the caller methods and solve them.
putting a general handler is not good for my case. I want to ignore some exceptions and let the app continue working.
Is there any tool or plugin in Visual Studio for this purpose?
Update: to clarify my question: there are lots of method calls without using try catch, I want to know where are these, automatically, without checking all line of codes
The simplest answer is to use a try-catch statement. You wrap the code you want to run in the try, and set the catches below the try. Any exceptions can be handled in the catches, and you can allow the program to continue to run. Your catches should be ordered from the most specific to the most generic last.
try
{
...code to be run
}
catch(Exception ex)
{
\\handle your exceptions here, you can add as many catches as you need.
Console.WriteLine(ex);
}
Read more here on MSDN for try-catch
Unlike Java, C# does not have checked exceptions (whether this is a good thing is debated; I think it is). I see a few options to figure out which methods throw what:
Hope the author documented them with /// <exception cref="SomeException">Some explanation</exception> so they'll show up in IntelliSense. All the framework code has fully documented exceptions.
Examine the source or decompiled IL yourself.
Use a utility like Exception Reflector to inspect possible exceptions.
The initial comments make some very valid points but if you still want to go down this route you can try the following.
If you know the exceptions that you want to ignore i would suggest adding those to your try catch
Consider the following
try
{
//Run Code here
}
catch (ArgumentNullException ane)
{
// ignore exception here
}
catch (AggregateException ae)
{
//ignore exception here
}
catch (Exception genericException)
{
// this must be last to catch unhandled exceptions
}
Actually after re-reading your initial post my answer is not entirely appropriate, it means you have to modify your code and enclose your method calls in the try catch..
I want to see exception detail in visual studio debugger without assigning variable to exception. Currently I have to write something like this:
try
{
//some code
}
catch (SecurityException ex)
{
//some code or ever no any code
}
Visual studio throws an error indicating that ex variable is never used, but i need this variable to see exception detail while debugging.
UPDATE: I know how to suppress VS error 'variable is never used', problem is in seeing exception inside watch without this variable.
$exception variable by #VladimirFrolov or exception helper by #MarcGravell is an answer.
You can see your exception in Locals list or use $exception in Watch list:
try
{
// some code
}
catch (SecurityException)
{ // place breakpoint at this line
}
You don't need to do anything: just put a breakpoint inside the catch (or on a catch and step once into the block) and you should see an invitation to see the exception helper. This works for naked catch or for type-specific catch(SecurityException) blocks:
which gives you everything:
At any moment when you hit the exception you can check the Watch Window and add variable: $exception.
This will let you work with all the Exception metadata.
You can use a functionality from Visual Studio.
Debug => Exceptions => Check "Common Language Runtime Exceptions"
That's it. Hope it helps.
use
catch (SecurityException /*without variable*/)
{/*break Point*/
//some code or ever no any code
}
or
catch /*without parameter*/
{/*break Point*/
//some code or ever no any code
}
but i think this is what you mean
catch (SecurityException ex)
{
MessageBox.Show(ex.ToString()); //for Winforms
Console.WriteLine(ex); //for console
}
just write
catch
{//set breakpoint here
}
To avoid getting the warning: "The variable 'ex' is declared but never used" in a catch statement,do the following:
try
{
}
catch (Exception)
{
// set break point
}
Or use System.Diagnostics.Debug.WriteLine() or Enable tracing or debugging to use a trace listener.
I got some weird error with response.redirect() and the project wasn't building at all.. when I removed the try-catch block that was surrounding the block of code where Response.Redirect() was in it worked normally..
Just want to know if this is a known issue or something...
If I remember correctly, Response.Redirect() throws an exception to abort the current request (ThreadAbortedException or something like that). So you might be catching that exception.
Edit:
This KB article describes this behavior (also for the Request.End() and Server.Transfer() methods).
For Response.Redirect() there exists an overload:
Response.Redirect(String url, bool endResponse)
If you pass endResponse=false, then the exception is not thrown (but the runtime will continue processing the current request).
If endResponse=true (or if the other overload is used), the exception is thrown and the current request will immediately be terminated.
As Martin points out, Response.Redirect throws a ThreadAbortException. The solution is to re-throw the exception:
try
{
Response.Redirect(...);
}
catch(ThreadAbortException)
{
throw; // EDIT: apparently this is not required :-)
}
catch(Exception e)
{
// Catch other exceptions
}
Martin is correct, a ThreadAbortException gets thrown when you use a Response.Redirect, see the kb article here
You may have referenced a variable that is declared inside the try block.
For example, the below code is invalid:
try
{
var b = bool.Parse("Yeah!");
}
catch (Exception ex)
{
if (b)
{
Response.Redirect("somewhere else");
}
}
You should move out the b declaration to outside the try-catch block.
var b = false;
try
{
b = bool.Parse("Yeah!");
}
catch (Exception ex)
{
if (b)
{
Response.Redirect("somewhere else");
}
}
I don't think there is any known issue here.
You simply can't do a Redirect() inside a try/catch block because Redirect leaves the current control to another .aspx (for instance), which leaves the catch in the air (can't come back to it).
EDIT: On the other hand, I might have had all of this figured backwards. Sorry.