Set an exception breakpoint for all exceptions except task cancellation - c#

I want to set a breakpoint in my C#/Xamarin Studio project that breaks on all exceptions, EXCEPT those that have to do with task cancellation. Is that possible?

You should use separate catch for CancellationException
try
{
//do your stuff here
}
catch(CancellationException ex)
{
//behave cancellation
}
catch(Exception ex)
{
//Here handle other exceptions
//Also you can put break point here
}

If you know your entry point exactly, you could write a code like this:
try
{
....
}
catch (CancellationException)
{
throw;
}
catch (Exception ex)
{
//otherwise handle this exception
}
If not, you could catch at application domain level using the event
ApplicationDomain.UnhandledException. More details here: http://developer.xamarin.com/api/event/System.AppDomain.UnhandledException/

I think it is possible. You may add catching all exceptions listening to System.Exception. Add the condition and check the type of exception in order to skip task cancelled exceptions. Exception in the local scope is available as $exception, so the condition will look like !($exception is System.Threading.Tasks.TaskCanceledException)

Related

Is it ok to handle specific exception like this

I have seen such code in many places, is there any benefit of this..Or this is a wrong practice..
try
{
......
}
catch (NullReferenceException ex)
{
Data.LogError(ex, "Exception occourred while ...");
}
catch (IndexOutOfRangeException ex)
{
Data.LogError(ex, "Exception occourred while ...");
}
catch (Exception ex)
{
Data.LogError(ex, "Exception occourred while ...");
}
In context of specific exception handling.
There is benefit if you are going to handle the exceptions differently in the catch block (i.e. perform different actions as a result of the exception being thrown).
Otherwise you could remove the more specific exception handlers and just use the most generic:
catch(Exception ex)
Note: If the exception is being used purely for logging then sometimes it can be useful to re-throw the exception to bubble it up to the rest of the application:
try{
}
catch(Exception ex){
// Log exception here
throw;
}
This is even better than a generic catch, because you can choose what to do with a certain type of exception. Say, you want to show a message if a file doesn't exist, and offer to retry, but kill the application otherwise.
You can also handle exceptions differently, because they offer different properties (thanks to Rots for pointing that out):
try
{
}
catch(FileNotFoundException ex)
{
Console.WriteLine(ex.FileName + " not found");
//Retry
}
catch(Exception ex) // Exception does not contain ex.FileName
{
//Save stuff
//Exit
}
Only the first matching block will be executed.
The given approach is best in case if you wanted to handle/log any specific exception in it's own way. Also, ideal in scenario, where you can inform user with more apt details than giving generic messages. Now, if you don't want to handle different exceptions then you can goahead with one catch block, which catch all exception.

Try Catch handled at top of process

if I do this:
try
{
//code
}
catch (Exception)
{
throw;
}
Does the Exception go up with all its information?
The idea is to handle errors at the top of the app. There I'd execute some SQL sp to fill the admin's table so he's aware of exceptions.
I want to store Exception.Message and the source (method, function, whatever..) of the exception. But I don't know how to refer to "where" the exception happened. Is it Exception.Source? Exception.TargetSite?
Thanks.
The type of Exception will tell you what kind of exception it is (IndexOutOfRangeException, SqlException, etc) which you would react too accordingly:
try
{
//code
}
catch (SqlException ex)
{
// Handle code
}
catch (IndexOutOfRangeException ex)
{
// Handle code
}
catch (Exception ex)
{
// Handle code
}
As to where it is happening... you should be enclosing exception-prone areas with a try catch and not large code chunks. This way you will know where the exception derives from.
The Short answer is yes: just calling throw passes everthing regarding the exception up.
throw ex resets the stack trace (so your errors would appear to originate from HandleException)
throw doesn't - the original offender would be preserved.
(quoted from Mark Gravell)

Is this try-catch block valid?

Newby question...
Is it valid to do:
try
{
// code which may fail
}
catch
{
Console.Writeline("Some message");
}
Or do I always have to use:
try
{
// code which may fail
}
catch (Exception e)
{
Console.Writeline("Some message");
}
Both blocks are valid.
The first will not have an exception variable.
If you are not going to do anything with the exception variable but still want to catch specific exceptions, you can also do:
try
{
// your code here
}
catch(SpecificException)
{
// do something - perhaps you know the exception is benign
}
However, for readability I would go with the second option and use the exception variable. One of the worst things to do with exceptions is swallow them silently - at the minimum, log the exception.
Yep, absolutely, such a catch block called general catch clause, see more interesting details in the C# Language Specification 4.0, 8.10 The try statement:
A catch clause that specifies neither an exception type nor an
exception variable name is called a general catch clause. A try
statement can only have one general catch clause, and if one is
present it must be the last catch clause
Yes, your first block of code valid. It will catch all exceptions.
It is. It will catch all the exception. So the two code examples do the same.
First one is valid, and it acts just like the second one.
http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.80%29.aspx
The catch clause can be used without arguments, in which case it
catches any type of exception, and referred to as the general catch
clause. It can also take an object argument derived from
System.Exception, in which case it handles a specific exception.
Yes it is valid.
you can always refer to this article:
Best Practices for Handling Exceptions on MSDN
Of course it is valid, you specify catch(Exception e) when you want to output the error message ex.Message, or to catch a custom or a concrete Exception. Use catch in your situation.
As #David answered this is valid.
You could use second syntax if you want to get more infos or catch a specific exception.
E.g.
catch (Exception e)
{
Debug.Print(e.Message);
}
catch (Exception e)
{
Console.Writeline("Some message");
}
In this block you can use SqlException, etc..
catch (SqlException e)
{
Console.Writeline("Some message");
}
For this use the "(SqlException e)"
If you will use a generic menssage, use this:
catch
{
Console.Writeline("Some message");
}
or
catch (Exception)
{
Console.Writeline("Some message");
}
Don't forget that you can chain catch your exceptions. This will allow you to handle different scenarios based upon the exception(s) the code may throw.
try
{
//Your code.
}
catch(SpecificException specificException)
{
//Handle the SpecificException
}
catch(AnotherSpecificException anotherSpecificException)
{
//Handle AnotherSpecificException
}
catch(Exception exception)
{
//Handle any Exception
}

C# try..catch - redirecting error handling flow from one catch to the next

I have a try..catch block that looks like this:
try
{
...
}
catch (IOException ioEx)
{
...
}
catch (Exception ex)
{
...
}
I'd like to handle just a certain kind of IOException, namely a sharing violation (Win32 0x20). Other IOExceptions and all other Exception descendants should be handled generally by the second catch-all catch.
Once I know that the IOException is not a sharing violation, how can I cleanly redirect the error handling flow to the general catch? If I rethrow in catch (IOException) the second catch does not invoke. I know I can nest try..catches but is there a cleaner way?
EDIT: On factoring-out handler logic
Factoring repeated code in methods will surely work, but I noticed that in general when you use factored methods for exception handling it tends to have subtle problems.
First of all, a catch clause has direct access to all of the local variables prior to the exception. But when you "outsource" exception handling to a different method then you have to pass the state to it. And when you change the code so does the handler method's signature changes, which might be a maintainability issue in more complicated scenarios.
The other problem is that program flow might be obscured. For example, if the handler method eventually rethrows the exception, the C# compiler and code analyzers like Resharper don't see it:
private void Foo()
{
string a = null;
try
{
a = Path.GetDirectoryName(a);
System.Diagnostics.Debug.Print(a);
}
catch (Exception ex)
{
HandleException(ex, a); //Note that we have to pass the "a"
System.Diagnostics.Debug.Print(
"We never get here and it's not obvious" +
"until you read and understand HandleException"
);
...!
}
}
static void HandleException(Exception ex, string a)
{
if (a != null)
System.Diagnostics.Debug.Print("[a] was not null");
throw (ex); //Rethrow so that the application-level handler catches and logs it
}
VS
private void Bar()
{
string a = null;
try
{
a = System.IO.Path.GetDirectoryName(a);
System.Diagnostics.Debug.Print(a);
}
catch (Exception ex)
{
if (a != null)
System.Diagnostics.Debug.Print("[a] was not null");
throw; //Rethrow so that the application-level handler catches and logs it
System.Diagnostics.Debug.Print(
"We never get here also, but now " +
"it's obvious and the compiler complains"
);
...!
}
}
If I want to avoid these kind of (minor) problems then it seems that there is no cleaner way than nesting try..catch blocks, as Hank pointed out.
Just factor the handling logic into a separate method.
try
{
...
}
catch (IOException ioEx)
{
if (sharing violation)
HandleSharingViolation();
else
HandleNonsharingViolation();
}
catch (Exception ex)
{
HandleNonsharingViolation();
}
Or test the exceptions yourself
catch (Exception ex)
{
if (ex is IOException && ex.IsSharingViolation()
HandleSharingViolation();
else
HandleNonsharingViolation();
}
No, you'll have to nest.
Once you are in 1 of the catch blocks, this 'try' is considered handled.
And I think it may make a lot of sense, "sharing violation" sounds like a special case that probably isn't so tightly coupled to the rest as you might be thinking. If you use nest try-catch, does the try block of the special case has to surround the exact same code? And of course it's a candidate to refactor out as a separate method.
Create Method to handle exception, pass the exception to that method , based on the type Handle the exception in the way you want.Call these method in both these blocks.
Use nested try catch blocks.
try
{
try
{
}
catch (IOException ioEx)
{
if (....)
else
throw;
}
}
catch
{
}
what about "finally"?
you can first set a 'variable' in the IOException block once you know the IOException is not sharing violation. Then, in your finally block, if that 'variable' is set, you proceed to do whatever you need to do.
Below impl. tested and confirmed.
bool booleanValue = false;
try
{
test1(); // this would thro IOException
}
catch (IOException e)
{
booleanValue = true; // whatever you need to do next
}
finally
{
if (booleanValue)
{
Console.WriteLine("Here");
}
}
Tryout this nested block
try
{
}
catch(Exception ioex)
{
try
{
}
catch(Exception ex)
{
}
}

Can I execute multiple Catch blocks?

This is a bit abstract, but is there any possible way to throw an exception and have it enter multiple catch blocks? For example, if it matches a specific exception followed by a non-specific exception.
catch(Arithmetic exception)
{
//do stuff
}
catch(Exception exception)
{
//do stuff
}
It is perfectly acceptable to have multiple catch blocks of differring types. However, the behavior is that the first candidate block handles the exception.
It will not enter BOTH catch blocks. The first catch block that matches the exception type will handle that specific exception, and no others, even if it's rethrown in the handler. Any subsequent ones will be skipped once an exception enters a catch block.
In order to have an exception caught in BOTH blocks, you would need to either nest blocks like so:
try
{
try
{
// Do something that throws ArithmeticException
}
catch(ArithmeticException arithException)
{
// This handles the thrown exception....
throw; // Rethrow so the outer handler sees it too
}
}
catch (Exception e)
{
// This gets hit as well, now, since the "inner" block rethrew the exception
}
Alternatively, you could filter in a generic exception handler based on the specific type of exception.
No. It isn't possible to execute the code in both catch blocks for a single exception.
I would probably refactor the code in the generic exception block into something that can be called from either.
try
{
// blah blah blah
{
catch(Arithmetic ae)
{
HandleArithmeticException( ae );
HandleGenericException( ae );
}
catch(Exception e)
{
HandleGenericException( e );
}
Like others said the exception will be caught by the most specific catch block.
This brings up a frustration of mine though with exception handling. I wish you could do something like
catch (ArgumentNullExcpetion, ArugmentOutOfRangeException ex)
{
}
Instead of having to do
catch (ArgumentNullExcpetion e)
{
}
catch (ArugmentOutOfRangeException outOfRange)
{
}
I understand the reasoning against this that you probably do different things for different exceptions but sometimes I want combine them.
You can't have more than one exception block handle the same exception. But what you can do is catch the general exception, then attempt to cast to the more specific, like this:
catch (Exception exception)
{
var aex = exception as ArithmeticException
if (aex != null)
{
// do stuff specific to this exception type
}
// then do general stuff
}
If you were using VB.NET you could abstract your error handler in the Arithmetic exception into a function or method call that always returns false.
Then you could write something like:
Catch ex as Arithmetic When HandleArithmetic()
Catch ex as Exception
End Try
Not that I would advocate such usage, though I have seen it recommended for logging purposes before. I don't believe there is a C# equivalent.
This is known as exception filtering and isn't supported in C# (I'm told it is possible in VB.NET).
One work around would be to catch the general exception and then check the exception type in the catch block and do any specific processing on that before carrying on with the rest of the block.

Categories

Resources