Exception from within a finally block - c#

Consider the following code where LockDevice() could possibly fail and throw an exception on ist own. What happens in C# if an exception is raised from within a finally block?
UnlockDevice();
try
{
DoSomethingWithDevice();
}
finally
{
LockDevice(); // can fail with an exception
}

Exactly the same thing that would happen if it wasn't in a finally block - an exception could propagate from that point. If you need to, you can try/catch from within the finally:
try
{
DoSomethingWithDevice();
}
finally
{
try
{
LockDevice();
}
catch (...)
{
...
}
}

The method is called Try / Catch
Where is your catch?
UnlockDevice();
try
{
DoSomethingWithDevice();
}
catch(Exception ex)
{
// Do something with the error on DoSomethingWithDevice()
}
finally
{
try
{
LockDevice(); // can fail with an exception
}
catch (Exception ex)
{
// Do something with the error on LockDevice()
}
}

Related

C# Monitor.Exit in Try/Catch

I am troubleshooting old source code, and came across a statement like this:
if (Monitor.TryEnter(lockObj))
{
try
{
//does something
if (failing_condition)
{
Monitor.Exit(lockObj);
throw new Exception("Oops!");
}
catch (Exception ex)
{
throw ex;
}
finally
{
Monitor.Exit(lockObj);
}
}
}
The code is crashing with a System.Threading.SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code.
Is there a safe way to call Monitor.Exit() on both the failing condition and when normal execution finishes?
Just do it in the finally block, its always runs even if an exception is thrown above. Also the catch section is unnecessary.
if(Monitor.TryEnter(lockObj)) {
try {
//does something
if(failing_condition) {
throw new Exception("Oops!");
}
}
finally {
Monitor.Exit(lockObj);
}
}

Reuse catch for all catches

is it possible to do something like the following:
I want to catch a custom exception and do something with it - easy: try {...} catch (CustomException) {...}
But then i want to run the code used in the "catch all" block still run some other code which is relevant to all catch blocks...
try
{
throw new CustomException("An exception.");
}
catch (CustomException ex)
{
// this runs for my custom exception
throw;
}
catch
{
// This runs for all exceptions - including those caught by the CustomException catch
}
or do i have to put whatever i want to do in all exception cases (finally is not an option because i want it only to run for the exceptions) into a separate method/nest the whole try/catch in another (euch)...?
I generally do something along the lines of
try
{
throw new CustomException("An exception.");
}
catch (Exception ex)
{
if (ex is CustomException)
{
// Do whatever
}
// Do whatever else
}
You need to use two try blocks:
try
{
try
{
throw new ArgumentException();
}
catch (ArgumentException ex)
{
Console.WriteLine("This is a custom exception");
throw;
}
}
catch (Exception e)
{
Console.WriteLine("This is for all exceptions, "+
"including those caught and re-thrown above");
}
Just do the overall catch and check to see if the exception is that type:
try
{
throw new CustomException("An exception.");
}
catch (Exception ex)
{
if (ex is CustomException)
{
// Custom handling
}
// Overall handling
}
Alternately, have a method for overall exception handling that both call:
try
{
throw new CustomException("An exception.");
}
catch (CustomException ex)
{
// Custom handling here
HandleGeneralException(ex);
}
catch (Exception ex)
{
HandleGeneralException(ex);
}
No, it doesn't do this way, you either catch a specific exception (linearly) or a generalisation. If you wish to run something for all exceptions you would need to keep a record of whether or not an exception has been thrown, perhaps what it was etc, and use finally, or another contrived, probably more 'messy' and verbose, mechanism.

Execution of multiple catch blocks [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
executing multiple catch blocks
Can multiple catch blocks be executed for a single try statement?How can we handle the catch blocks?Can we create try without catch block??
There can be multiple catch blocks (as said in other answers already), but only the one that first matches the exception type is executed. That means you need to order the catch blocks properly. For example:
try
{
}
catch (Exception exp1)
{
// Block 1
}
catch (IOException exp2)
{
// Block 2
}
Block 2 will never be executed, as block 1 catches every exception (all exception classes are derived from Exception).
try
{
}
catch (IOException exp1)
{
// Block 1
}
catch (Exception exp2)
{
// Block 2
}
In this example, block 2 will only be executed if the exception is not an IOException or derived from IOException. If an IOException is thrown, only block 1 will execute, block 2 will not.
You can have multiple catch blocks associated with a try block,but only a single catch block can ever handle your exception.
Yes you can have a try block without a catch,but it is mandatory to have a
finally block
Technically you can only hit one catch BUT you say:
Can multiple catch blocks be EXECUTED for a single try statement
Keyword being executed. So, you could try:
catch (Exception ex)
{
if (ex is MyException1||
ex is MyException2)
{
//do stuff
}
else
{
throw;
}
}
Yes you can have multiple catch blocks with try statement. You start with catching specific exceptions and then in the last block you may catch base Exception. Only one of the catch block will handle your exception.
You can have try block without a catch block. try/finally will do.
try
{
Console.Write("test");
}
catch (IOException ex)
{
}
catch (ArithmeticException ex)
{
}
catch (Exception ex)
{
}
try without catch
try
{
}
finally
{
}
1 Yes it's possible to have multiple catch, one catch for one specific exception
Sample
try
{
...
}
catch (FormatException)
{
....
}
catch (OverflowException)
{
...
}
2 You can have try instrction without catch
try
{
...
}
Finally
{
.....
}
Only one catch block will execute, and it will be the catch that closely matches the type of the Exception that was thrown.
You can't have a try by it self. You need a try catch (one or more catch block) or a try finally or a try catch finally
You can have any number of catch block for a single try..catch statement.
But please remeber one thing, that your
catch (Exception ex)
{
...
}
Should be the last catch block, since all exceptions inherits the the class Exception.
As for the second part of your question, you can do either
try
{
stuff...
}
catch(Exception ex){}
or
try
{
stuff...
}
finally{}
, but you can't do try by itself.

Catch two exceptions in the same catch block?

I have a method that can throw two different exceptions, CommuncationException and SystemException. In both cases I do the same three-line code block.
try {
...
}
catch (CommunicationException ce) {
...
}
catch {SystemExcetion se) {
...
}
Is there any possibility to do it like that?
try {
...
}
catch (CommunicationException ce, SystemException se) {
...
}
Then I would not have to write this much code. I know I could extract the exception handling to a private method, but since the code is only 3 lines long, the method definition would take more code than the body itself.
If you can upgrade your application to C# 6 you are lucky. The new C# version has implemented Exception filters. So you can write this:
catch (Exception ex) when (ex is CommunicationException || ex is SystemException) {
//handle it
}
Some people think this code is the same as
catch (Exception ex) {
if (ex is CommunicationException || ex is SystemException) {
//handle it
}
throw;
}
But it´s not. Actually this is the only new feature in C# 6 that is not possible to emulate in prior versions. First, a re-throw means more overhead than skipping the catch. Second, it is not semantically equivalent. The new feature preserves the stack intact when you are debugging your code. Without this feature the crash dump is less useful or even useless.
See a discussion about this on CodePlex. And an example showing the difference.
In fact, you could catch only SystemException and it would handle CommunicationException too, because CommunicationException is derived from SystemException
catch (SystemException se) {
... //this handles both exceptions
}
Unfortunately, there is no way. The syntax you used is invalid and a fall through like in a switch-statement isn't possible either. I think you need to go with the private method.
A little hacky work-around would be something like this:
var exceptionHandler = new Action<Exception>(e => { /* your three lines */ });
try
{
// code that throws
}
catch(CommuncationException ex)
{
exceptionHandler(ex);
}
catch(SystemException ex)
{
exceptionHandler(ex);
}
You need to decide for yourself if this makes any sense.
No, you can't do it that way. The only way i know of is to catch a generic Exception and then check what type it is:
try
{
...
}
catch(Exception ex)
{
if(ex is CommunicationException || ex is SystemException)
{
...
}
else
{
... // throw; if you don't want to handle it
}
}
What about
try {
...
}
catch (CommunicationException ce) {
HandleMyError(ce);
}
catch {SystemExcetion se) {
HandleMyError(se);
}
private void HandleMyError(Exception ex)
{
// handle your error
}
Possible Duplicate of
Catch multiple exceptions at once?
I quote the answer here:
catch (Exception ex)
{
if (ex is FormatException ||
ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
else
{
throw;
}
}
Dragging this one up from the depths of history as it happened to pop up in some search results.
With the advent of C# 7.0 (which arrived in 2017 with VS2017, .net framework 4.7 and dotnet core 2.0) you can now do things like this:
try {
...
}
catch (Exception e) when (e is CommunicationException || e is SystemException) {
...
}
Since you're doing the same for both type of exceptions, you could just go:
try
{
//do stuff
}
catch(Exception ex)
{
//normal exception handling here
}
Only catch explicit Exception types if you need to do something unique for it.

Is the order of Catch blocks important?

Just making sure I understand it well. Is the correct schema correct? Catching the most specific exceptions first to catching broader exceptions with general catch at the end of the set of catch blocks.
try
{
some code
}
catch(SomeSpecificException ex)
{
}
catch(LessSpecificException ex)
{
}
catch
{
//some general exception
}
I believe it won't let you write it in the incorrect order.
This generates an error:
try
{
throw new OutOfMemoryException();
}
catch(Exception ex)
{
"B".Dump();
}
catch(OutOfMemoryException ex)
{
"A".Dump();
}

Categories

Resources