Why can I write a generic catch statement in C# that does nothing? [duplicate] - c#

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why can’t I catch a generic exception in C#?
I have been reviewing and writing Circuit Breaker code recently. The following method compiles, but the catch block is never entered. I have plenty of work-arounds, and this isn't the only way to get the right behavior (filtering exceptions), but I'm curious why this compiles and doesn't work!
public void AttemptCall<TException>(Action action)
where TException : Exception
{
try
{
action();
}
catch(TException e) // This block is never entered!
{
state.ActUponException(e);
throw;
}
}
Here is a test that should enter the catch block of the previous method.
[TestMethod]
public void Throw_an_exception()
{
circuitBreaker.AttemptCall<Exception>(() => throw new Exception());
// test the circuit breaker's state
}

Its a bug https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0

Related

How can I "use" a variable to stop an error message saying it's not used? [duplicate]

This question already has answers here:
The variable 'MyException' is declared but never used
(6 answers)
Closed 5 years ago.
My IDE is always opening up and giving me this message:
try
{
await Task.Delay(1000, App.tokenSource2.Token);
}
catch (TaskCanceledException ex) { ex = null; }
The variable ex is declared but never used.
I would like to avoid being the message. Any suggestions?
Just dont specify any variable if you are not planning to use it:
try
{
await Task.Delay(1000, App.tokenSource2.Token);
}
catch (TaskCanceledException) { ... }

Writing a function to handle exceptions in C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Is it reasonable to think I can write a void function to take in an Exception and output the stuff that a catch block normally would? Here's an example of my exception catcher (which I would make individual ones for common exceptions I handle):
private void exCatch(Exception ex)
{
MessageBox.Show("ERROR - " + blah blah blah + ex.ToString(), blah blah);
}
Here it is in practice:
try
{
stuff
}
catch (Exception e)
{
exCatch(e);
}
Is this an efficient way to handle exceptions? If this is reasonable, do people do this? It seems like it could speed up your coding not having to copy paste all your exception junk over and over. Thanks for any help!
There is no problem with that at all. In fact, adding functions to reduce code repetition is definitely advisable. Then if you want to change say the MessageBox buttons you change it once and you're done everywhere.
One note is that you should consider only catching certain types of exceptions that you're expecting. If you're catching an exception it should be because you know where it came from and exactly what to do with it. Or else you might be catching something that should be handled at a higher level and your app can get into an invalid state. Here's an example.
ArgumentNullException
FormatException
OverflowException
Are the exceptions that Int32.Parse(string) throws. Lets say you know you wont be passing in Null this is how MSDN shows you should handle the function:
using System;
public class Example
{
public static void Main()
{
string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
"0xFA1B", "163042", "-10", "007", "2147483647",
"2147483648", "16e07", "134985.0", "-12034",
"-2147483648", "-2147483649" };
foreach (string value in values)
{
try {
int number = Int32.Parse(value);
Console.WriteLine("{0} --> {1}", value, number);
}
catch (FormatException) {
Console.WriteLine("{0}: Bad Format", value);
}
catch (OverflowException) {
Console.WriteLine("{0}: Overflow", value);
}
}
}
}
https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx
Always look up the exceptions that a method can throw and always document those that you are catching and throwing in your methods.

SetValue property reflection Exception handling issues [duplicate]

This question already has answers here:
Why is TargetInvocationException treated as uncaught by the IDE?
(2 answers)
Closed 8 years ago.
When using property reflection to SetValue, the property throws a TargetInvocationException. However, since the call to SetValue is an invocation, the exception is caught and not handled in the property. Is there way to handle the Target Exception in the property and have it ONLY thrown in the main program?
I want this throw to be as if I just made a method call, not an invocation.
Edit for clarification:
The problem I am having is that within the reflect class, I am getting a debug message that says "Exception was unhandled by user code". I have to 'continue' with the debug session and the inner exception is the 'real' exception. Is this just to be expected? I dont want to get warned (and I dont want to hide warnings), I want the code to fix the warning.
public class reflect
{
private int _i;
public int i
{
get { return _i; }
set
{
try{throw new Exception("THROWN");}
catch (Exception ex)
{ // Caught here ex.Message is "THROWN"
throw ex; // Unhandled exception error DONT WANT THIS
}
}
}
}
class Program
{
static void Main(string[] args)
{
reflect r = new reflect();
try
{
r.GetType().GetProperty("i").SetValue(r, 3, null);
}
catch(Exception ex)
{ // Caught here, Message "Exception has been thrown by the target of an invocation"
// InnerMessage "THROWN"
// WANT THIS Exception, but I want the Message to be "THROWN"
}
}
}
You need the InnerException:
catch(Exception ex)
{
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
}
}
This isn't specific to reflection - it's the general pattern for any exception which was caused by another. (TypeInitializationException for example.)
Sorry, can't comment yet. Two things:
1) why are you first catching ex in your reflection class and then throwing it again? This shouldn't be the problem, though.
2) I think you are getting your exception. Check the "Exception has been thrown"'s inner exception.

how to test I need try catch [duplicate]

This question already has answers here:
How to test that no exception is thrown?
(20 answers)
Closed 8 years ago.
I m using NUnit, I have following code which will be tested.
public class StudentPresenter
{
IView myview;
Repository myrepo;
public StudentPresenter(IView vw, Data.Repository rep)
{
this.myview = vw;
this.myrepo = rep;
this.myview.ButtonClick += myview_ButtonClick;
}
public void myview_ButtonClick()
{
try
{
var d = this.myrepo.GetById(int.Parse(myview.GivenId));
this.myview.GetStudent(d);
}
catch(Exception e)
{
}
}
}
I need to test myview_ButonClick()
Lets suppose I will test this method and it will throw exception if myview.GivenId is null?
So I write unit test as below:
[Test]
public void Button1Click_NullText_ThrowException()
{
var mock = Substitute.For<IView>();
StudentPresenter sp = new StudentPresenter(mock, repo);
mock.GivenId = string.Empty;
Assert.Throws<Exception>(()=>sp.myview_ButtonClick());
}
But test failed.. Why? (becouse no throw in my catch block). But I dont want to throw anything, I just want that it has to ability to catch. So is it possible to test?
You cannot have a unit test that checks if a code block has a "catch" block. The only way to (indirectly) do it would be to test that the test does not throw when given input that would normally cause it to throw.
NUnit has a DoesNotThrow assert that should be useful here.
Of course, that's no guarantee of the existence of a try/catch, but its about the best you can do.
myview_ButtonClick() catches all exceptions, and so it will never throw an exception that could be detected from outside the method, hence your test fails.
If you want to catch the exception, do something with it, and then throw it in order for a caller to catch it, or the test to pass, then simply
catch (Exception e)
{
//actions....
throw;
}
Bear in mind too that catching all exceptions is rarely a good idea. The calling code will continue oblivious to the exception state, and this could cause untold problems down the line, which could be a nightmare to debug and track down.

Are there any circumstances under which the finally block does not get executed? [duplicate]

This question already has answers here:
Will code in a Finally statement fire if I return a value in a Try block?
(12 answers)
Does the C# "finally" block ALWAYS execute? [duplicate]
(11 answers)
Closed 9 years ago.
Please note this code:
class CTestFinally
{
public static void Run()
{
try
{
TryAndTry();
}
catch (Exception exError)
{
Console.WriteLine(exError.Message);
}
finally
{
Console.WriteLine("Finally...!");
}
Console.ReadKey();
}
static void TryAndTry()
{
try
{
TryAndTry();
}
catch (Exception exError)
{
Console.WriteLine(exError.Message);
}
finally
{
Console.WriteLine("Try: Finally...!");
}
}
}
}
Finally never executed because we get stack overflow Error.
Are there any circumstances under which the finally block does not get executed other than
above problem?
StackOverflowException is one of the few kinds of exception that a CLR host typically treats specially. ASP.NET will kill the worker process for example. This is very hard to debug because your app just goes away. SQL Server has similar policies I'm sure (like unloading the appdomain).
The reason for that is that this is a destabilizing condition that does not allow for reliable error recovery (after all your stack is unusable! You can for example not call your logger or send an email. There is no room on the stack.).
Another of this kind is OutOfMemoryException (you can't even allocate an Exception - that's why the CLR pre-allocates one OOM instance...). I think ASP.NET tolerates this while SQL Server kills your appdomain.
For normal exceptions this works fine.
This will never execute the finally:
using System;
namespace Demo
{
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
try
{
Console.WriteLine("In try");
Environment.FailFast("Aaaaaargh");
}
finally
{
Console.WriteLine("In finally");
}
}
}
}

Categories

Resources