Assert in Try..Catch block is caught - c#

Just came across some interesting behavior - Assert being caught by Catch block.
List<Decimal> consArray = new List<decimal>();
try
{
Decimal d;
Assert.IsTrue(Decimal.TryParse(item.Value, out d));
consArray.Add(d);
}
catch (Exception e)
{
Console.WriteLine(item.Value);
Console.WriteLine(e);
}
Assert throws AssertFailedException and its caught by catch. Always thought that if Assert fails then test is failed and consecutive execution is aborted. But in that case - test moves along. If nothing wrong happens later - I get green test! In theory - is it right behavior?
Edited: I understand that maybe it is .NET restriction and how asserts are made in MsTest. Assert throws exception. Since catch - catches everything it catches assert exception. But is it right in theory or MsTest specific?

As already answered, this is correct behavior. You can change your code to get Your expected behavior by catching the AssertFailedException and re-throwing it.
List<Decimal> consArray = new List<decimal>();
try
{
Decimal d;
Assert.IsTrue(Decimal.TryParse(item.Value, out d));
consArray.Add(d);
}
catch (AssertFailedException)
{
throw;
}
catch (Exception e)
{
Console.WriteLine(item.Value);
Console.WriteLine(e);
}

NUnit will do the exact same thing. As should any other test framework I think, but I only know MStest and NUnit in C#.
I'd expect that your test code would not contain Decimal.TryParse, but your business logic would do that, which you'd test with an object and a method call.
Something like:
var sut = new Sut();
var d = sut.DoSomethingThatReturnsTheDecimal(item.Value);
Assert.AreEqual(0.123, d, string.Format("passed value can not be parsed to decimal ({0})", item.Value);
In order to stay a bit closer to your implementation:
List<Decimal> consArray = new List<decimal>();
Decimal d = Decimal.MinValue;
// You don't need to try-catch a Decimal.TryParse
// Decimal.TryParse(item.Value, out d));
try
{
d = Decimal.Parse(item.Value)
}
catch
{
// Handle exception
}
Assert.AreEqual(0.123, d);
// Does the list add anything at all? In this sample it seems a bit redundant
consArray.Add(d);
Anyway, to answer your question. The try-catch is supposed to catch your AssertFailedException.
PS: Catching the AsserFailedException and re-throwing it will also work, but it feels a bit strange to me. I'd strive to leave the Asserts outside any try-catch blocks. But that might be just my opinion which you didn't ask for :).

Your code is working as expected. When an Assert fails it throws an AssertFailedException which
inherits from Exception. So you can add a try-catch and catch it.
In your case, add a throw at the end of the catch and re-throw the exception.

Related

Correct method for testing for an exception using Moq and MSTest

A little confusion as to the behaviour of Moq with MsTest.
Edit: This is not a question of "How do I test?" or "How do I assert?", this is a scratch pad to see how MoQ works so don't focus on the exception type etc.
I think a better question may be => "Does Moq Throws<> behave similar to MsTest ExpectedExceptionAttribute?" That is, they're expecting an exception in the test or the SUT?
I'd like to know just how MoQ "Throws" works when used with MsTest. Is it better to not use the MsTest expected exception attribute? Is it better to perform a try..catch within the test? I have a few more questions surrounding this.
I am Mocking a database call and when an error occurs I would like to return zero (0).
The TestMethod is straight forward with the MsTest exception attribute, and the throws exception with Moq. It only works when I throw an exception within the SaveCart method and not when I return zero.
I would like to understand the underlying behaviour because it feels as though I shouldn't, nor want to throw an exception within the SaveCart method.
Here is the Test under question:
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void CartRepoSaveCartExceptionShouldReturnZero()
{
_cartDatabaseMock.Setup(c => c.SaveCart(_cart))
.Throws<ApplicationException>();
var result = _cartRepository.SaveCart(_cart);
Assert.AreEqual(result, _cartSaveExceptionValue);
}
Here is the basic SaveCart which does NOT throw an exception causing the test to fail:
public long SaveCart(Cart cart )
{
long returnValue;
try
{
returnValue = _cartDatabase.SaveCart(cart);
}
catch (Exception)
{
return 0;
}
return returnValue;
}
Here is a basic SaveCart where the test works because it's throwing an exception:
public long SaveCart(Cart cart )
{
long returnValue;
try
{
returnValue = _cartDatabase.SaveCart(cart);
}
catch (Exception)
{
throw new ApplicationException();
}
return returnValue;
}
Feel free to suggest a better title for the question if it doesn't quite explain it clearly.
You should use ExpectedExceptionAttribute when the unit under test throws an exception.
In your first example the method didn't throw any exception therefore the test failed.
Since your method under test doesn't throw any exception you don't need to use this attribute at all...(just verify the return value in this scenario)
When you want to verify that exception was thrown and you want to verify that some additional operations occurred, use the following pattern:
[TestMethod]
[ExpectedException(typeof(<The specific exception>))]
public void FooTest()
{
//arrange
try
{
// act
}
catch(<the specific exception>)
{
// some asserts
throw;
}
}
The above snippet will failed if:
wrong exception raised
exception was not raised
one of your asserts failed.
BTW, since your catch in the method is no Exception instead of ApplicationException, I offer you to change the setup to:
_cartDatabaseMock.Setup(c => c.SaveCart(_cart)).Throws<Exception>();
You are right - the second test "SaveCart" works because it's throwing an exception and the the first test fail because you are turning 0. From your response to previous answers, I am sure you already know all of this. If you are asking for the behavior how it failed your first test... it goes like this:
SaveCart is called
It returns an exception (result of your moq setup)
Your try catch caught the exception (you did this on purpose to alter the result)
Your try catch returns 0 (result is now 0 as you intended to alter it)
Assert checks your result against _cartSaveExceptionValue
You get a fail test stating something similar to this "Message: Assert.AreEqual failed. Expected. Actual<0 (System.Int32)>."
If you want to double check this... you can try the following test
comment out the [ExpectedException(typeof())]
change the Assert.AreEqual(result, _cartSaveExceptionValue) to Assert.AreEqual(result, 0);
the test should pass because you are comparing "result" (aka 0) to 0
I hope this answer your question.
catch (Exception)
{
return 0;
}
you are not throwing the exception, rather swallowing the exception, so why would you expect exception? It has nothing to do with MOQ. Your test and code are not in sync.
This is a bad practice btw, to swallow exception.
catch (Exception)
{
throw new ApplicationException();
}
That's also a code smell. You are catching all kinds of exception and then throwing a different type.

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.

Is it good to use try catch within a try catch? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are nested Try/Catch blocks a bad idea?
Currently I am using try catch within try catch ? The current senario requires it in our application.
void MyFun()
{
try
{
//Process logic 1
// ......
try
{
//Process logic 2
// ......
} catch (Exception ex)
{
//write an error details in database
}
//Process Logic 3
// ......
} catch (Exception ex)
{
//show error msg
}
}
No particular problem with this especially if you want to handle the exceptions differently.
However, if the inner exception and the outer exception are of different types E1, E2 respectively and E1 is not a parent of E2, you can have two adjacent catch clauses.
try
{
// do something
}
catch (E1 e1)
{
}
catch (E2 e2)
{
}
As noted by Rob and J.Steen - this is slightly different than the case in the question as in this case is E1 is thrown the code after it will not be executed.
A nested try/catch is fine. what you want to stay away from is changing the logical flow of your code based on the try catch. In other words, you shouldn't treat a try/catch as an if/else block. so this isn't ideal:
//over the top example just to demonstrate my point
public bool IsNumberTen(int x)
{
try
{
if(x > 10)
throw new NumberTooHighException();
else if(x < 10)
throw new NumberTooLowException();
else
return true;
}
catch(NumberTooHighException)
{
return false;
}
catch(NumberTooLowException)
{
return false;
}
}
This item suggests that its not a bad thing and that you would only have to handle the error in another way any way.
Exception handling try catch inside catch
I don't see why not. If you have logic in the catch which may fail or raise an exception that requires handling then it makes sense.
Its a little difficult to answer this question without knowing what logic is in here.
Certainly in terms of performance, nested exception handling will incur a greater cost, but general rule of thumb is only catch exceptions that you as a developer understand how to handle. This overlaps into the practice of TDD where if you have a good enough set of tests you can identify where the expected exceptions should be, then this will dictate your exception logic.
I would say this: it's not bad. Whether it's good depends on your program, and whether such a concept makes sense given your method's logic and contracts.
Edit: I'd suggest checking out the article Exception Cost: When to throw and when not to. It outlines what is most expensive for exception management in the CLR.
I am trying to think of situations where you may want a nested block... perhaps if you are making database changes and you are using the try catch as a virtual transaction, you may want to try to update some properties but then carry on if that fails, but also catch an overall exception if and when you actually commit to the database update itself.
Even with this considered, you should never need to do this... It should be perfectly sufficient to simply stack blocks next to each other like so:
void MyFun()
{
try
{
//Process logic 1
// ......
} catch (Exception ex)
{
//show error msg
}
try
{
//Process logic 2
// ......
} catch (Exception ex)
{
//write an error details in database
}
}
It is also probably worth noting that if you find the need to nest try catch blocks then there is probably a better way you could be designing your code.
EDIT: Itay's answer is also somewhat better than nesting, although it will not allow you to carry on in the block once you have caught an exception.
Hope this helps!

C# try catch continue execution

I have a question that might seem fairly simple (of course if you know the answer).
A certain function I have calls another function but I want to continue execution from the caller even though the callee has thrown an exception. Let me give you an example:
something function1()
{
try
{
//some code
int idNumber = function2();
//other code that need to execute even if function2 fails
return something;
}
catch(Exception e)
{//... perhaps something here}
}
EDIT: function1 also has a return statement so nothing can in fact crash on the way
In function2 I need to do stuff but I only need to log if anything fails, example:
int function2()
{
try
{
//dostuff
}
catch(Exception e)
{
//Log stuff to db
}
}
ok, now my question is, what should I do if I wanted to continue execution in function1 even if function 2 throws an error?
Sometimes I mix up if I should do throw; or throw e; or throw nothing at all (leave catch block empty)
Leaving the catch block empty should do the trick. This is almost always a bad idea, though. On one hand, there's a performance penalty, and on the other (and this is more important), you always want to know when there's an error.
I would guess that the "callee" function failing, in your case, is actually not necessarily an "error," so to speak. That is, it is expected for it to fail sometimes. If this is the case, there is almost always a better way to handle it than using exceptions.
There are, if you'll pardon the pun, exceptions to the "rule", though. For example, if function2 were to call a web service whose results aren't really necessary for your page, this kind of pattern might be ok. Although, in almost 100% of cases, you should at least be logging it somewhere. In this scenario I'd log it in a finally block and report whether or not the service returned. Remember that data like that which may not be valuable to you now can become valuable later!
Last edit (probably):
In a comment I suggested you put the try/catch inside function2. Just thought I would elaborate. Function2 would look like this:
public Something? function2()
{
try
{
//all of your function goes here
return anActualObjectOfTypeSomething;
}
catch(Exception ex)
{
//logging goes here
return null;
}
}
That way, since you use a nullable return type, returning null doesn't hurt you.
Why cant you use the finally block?
Like
try {
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
EDIT after question amended:
You can do:
int? returnFromFunction2 = null;
try {
returnFromFunction2 = function2();
return returnFromFunction2.value;
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
if (returnFromFunction2.HasValue) { // do something with value }
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
Or you can encapsulate the looping logic itself in a try catch e.g.
for(int i = function2(); i < 100 /*where 100 is the end or another function call to get the end*/; i = function2()){
try{
//ToDo
}
catch { continue; }
}
Or...
try{
for(int i = function2(); ; ;) {
try { i = function2(); return; }
finally { /*decide to break or not :P*/continue; } }
} catch { /*failed on first try*/ } finally{ /*afterwardz*/ }
just do this
try
{
//some code
try
{
int idNumber = function2();
}
finally
{
do stuff here....
}
}
catch(Exception e)
{//... perhaps something here}
For all intents and purposes the finally block will always execute. Now there are a couple of exceptions where it won't actually execute: task killing the program, and there is a fast fail security exception which kills the application instantly. Other than that, an exception will be thrown in function 2, the finally block will execute the needed code and then catch the exception in the outer catch block.
Do you mean you want to execute code in function1 regardless of whether function2 threw an exception or not? Have you looked at the finally-block? http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
In your second function remove the e variable in the catch block then add throw.
This will carry over the generated exception the the final function and output it.
Its very common when you dont want your business logic code to throw exception but your UI.

How do I catch and ignore or handle an exception while reading data from a text file line by line

I am reading a file line by line from text file and do some processing. The problem is that if some error occurs at some line. Then an exception is generated, what I want is that I want to ignore that error and move to the next line to read.
But if an exception is generated then I cant continue reading input lines. Please help.
If I'm assuming what you're asking for correctly, here's a basic outline of what your code could look like:
using (StreamReader reader = File.OpenText("Path\to\your\file"))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
try
{
ProcessLine(line);
}
catch { /* Ignore exceptions */ }
}
}
It's generally not a good idea to blindly catch all exceptions, so if you can, you should filter the exceptions caught by your catch block to something more specific.
See exception handling. http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.71).aspx
If you really want to "ignore" exceptions, you can do something like:
try
{
foo(); // Something that may throw an exception
}
catch
{
}
See http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx for more info.
But usually, an exception means something bad happened, and you'll probably want to handle that somehow.
try
{
//put the statement throwing the exception here
}
catch
{
//will eat the exception
}
//execution will continue here
Difficult to understand what you want to achieve, but you probably are asking for something like this:
while(condition)
{
try {
//process file line here
}
catch (Exception ex) {
LogException(ex);
}
}
Not a good design decision in my opinion, by the way. Avoid it if you can.
Use a try catch and log the error. Your code would look like this:
try
{
//read lines here
}
catch(Exception ex)
{
//log the exception but don't throw anything.
}
You may be tempted to do nothing in the catch, but you will likely regret it later.
Try catch article:
http://www.homeandlearn.co.uk/csharp/csharp_s5p6.html
You simply need to wrap your processing code in a try / catch block.
try
{
DoSomeProcessing(lineThatIreadFromFile);
}
catch
{
// Log or Ignore error here
}
However, please note that typically, just swallowing exceptions is never a good idea. You should either fail your program (if unrecoverable), or potentially log those somewhere so you can fix why your program is failing.
Based on the very limited information you provide there are two things you can do:
Enclose the offending line with an empty catch block. Wait for next maintainer to do bad things to you.
Understand why the exception is happening and modify the code such that the next maintainer understands why it is safe that you ignored a certain condition
This is not a good approach. You should be proactive and catch specific exceptions you can recover from. Catch them as close to the place where they are thrown from. And let the rest of them bubble up and terminate the process. By swallowing all exceptions you will get an illusion of robustness while in fact your code may be full of bugs. There is simply no 'quick and dirty' approach to exception handling. See this answer.
Avoid handling errors by catching non-specific exceptions, such as
System.Exception, System.SystemException, and so on, in application
code. There are cases when handling errors in applications is
acceptable, but such cases are rare.
An application should not handle exceptions that can result in an
unexpected or exploitable state. If you cannot predict all possible
causes of an exception and ensure that malicious code cannot exploit
the resulting application state, you should allow the application to
terminate instead of handling the exception.
You need:
using System.IO;
to get this to work.
You can try:
try
{
string path = ""; // You must add the path here. Else it won't work.
string[] lines = File.ReadAllLines(path);
foreach(string line in lines)
{
Console.WriteLine(line);
}
} catch (Exception ex, IOException ioex) {
// It's optional. You can remove "Exception ex, IOException ioex" if you want. You can delete the code below too.
Console.WriteLine(ex.ToString());
Console.WriteLine();
Console.WriteLine(ioex.ToString());
} finally
{
// in this "finally" section, you can place anything else. "finally" section isn't important, just shows that method has no exceptions.
// you can add something else like: Console.WriteLine("Code has no exceptions. Great!");
}
Good for advanced notepads.
EDIT: If you don't like the previous solution, this one can help you.
string path = ""; // Again, path.
string[] lines = File.ReadAllLines(path);
foreach(string line in lines)
{
try
{
Console.WriteLine(line);
} catch(Exception ex, IOException ioex)
{ /* exception */ }
}
----- or -----
string path = Console.ReadLine();
int turns = 0;
int maxturns = (File.ReadAllLines(path)).Count();
while (turns < maxturns)
{
try
{
Console.WriteLine(File.ReadLines(path).Skip(turns).Take(1).First());
} catch (Exception ex, IOException ioex) { /* exception */ }
turns++;
}

Categories

Resources