Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Feb 15th, 2008, 7:33 PM   #1
kurt
Programmer
 
Join Date: Oct 2005
Posts: 72
Rep Power: 4 kurt is on a distinguished road
How to "expect an exception to occur" in the best code-style

I am just looking for a better writing method to improve myself. So, the situation is this (i'm writing a test script to catch errors, where the situation is that I am expecting an exception to occur. It must):

bool errorMissing = true;

try
{
   // Some statement that MUST return an error
}
catch (Exception e)
{
   errorMissing = false; //error occured. Good!   
   // Then I check the error messages, etc to see if correct
}
finally
{
   if (errorMissing)
   {
      //Assert.Fail( )
   }
}
1. I hide the implementation, but the idea is there
2. Is there a better and more elegant way in C#?
kurt is offline   Reply With Quote
Old Feb 15th, 2008, 11:27 PM   #2
ScottyB
Newbie
 
ScottyB's Avatar
 
Join Date: Feb 2008
Location: Toowoomba, Australia
Posts: 7
Rep Power: 0 ScottyB is on a distinguished road
Re: How to "expect an exception to occur" in the best code-style

With exception handling in C# the try block is where you put the code that you expect may produce an exception.

The catch clauses are used to handle exceptions that are generated from within the try block.

The catch clause section can contain multiple exception handlers. When an exception occurs the catch clauses are searched in order from first to last. As a result when writing your catch clauses you should put the most specific exception handlers first followed by the more general ones.

In the example below if the specific handlers cannot handle the exception it is caught by the last handler. In this example I have caught the exception message. You can choose what to do with this message after the calling block.

Whether or not an exception occurs the finally block is always run. It is usually where your clean up code goes. You can put your code to close database connections or files that you have open in the try statement.


string errorMessage = String.Empty;

int d = 0;

try
{
// Generated Exception for Demonstration Purposes
float f = 1 / d;
}
// Catch specific exception firsts and work your way to the more general ones
catch (DivideByZeroException ze)
{
errorMessage = ze.Message;
}
catch (IOException ie)
{
errorMessage = ie.Message;
}
catch (SqlException se)
{
errorMessage = se.Message;
}
catch (Exception ge)
{
errorMessage = ge.Message;
}

finally
{
// Clean up code here
}

return errorMessage;


I hope this helps

Regards

Scottyb
ScottyB is offline   Reply With Quote
Old Feb 16th, 2008, 10:38 AM   #3
kurt
Programmer
 
Join Date: Oct 2005
Posts: 72
Rep Power: 4 kurt is on a distinguished road
Re: How to "expect an exception to occur" in the best code-style

Quote:
Originally Posted by ScottyB View Post
With exception handling in C# the try block is where you put the code that you expect may produce an exception.

The catch clauses are used to handle exceptions that are generated from within the try block.

The catch clause section can contain multiple exception handlers. When an exception occurs the catch clauses are searched in order from first to last. As a result when writing your catch clauses you should put the most specific exception handlers first followed by the more general ones.

In the example below if the specific handlers cannot handle the exception it is caught by the last handler. In this example I have caught the exception message. You can choose what to do with this message after the calling block.

Whether or not an exception occurs the finally block is always run. It is usually where your clean up code goes. You can put your code to close database connections or files that you have open in the try statement.


string errorMessage = String.Empty;

int d = 0;

try
{
// Generated Exception for Demonstration Purposes
float f = 1 / d;
}
// Catch specific exception firsts and work your way to the more general ones
catch (DivideByZeroException ze)
{
errorMessage = ze.Message;
}
catch (IOException ie)
{
errorMessage = ie.Message;
}
catch (SqlException se)
{
errorMessage = se.Message;
}
catch (Exception ge)
{
errorMessage = ge.Message;
}

finally
{
// Clean up code here
}

return errorMessage;


I hope this helps

Regards

Scottyb
Yeah, it sort of helps. Thanks Scottyb.

But my real intention is the see whether my command returns an exception or not? Like i said, i am writing a test function, and that particular command must return an exception as it is no longer supported. If it did not, i render the test as "failed".

My method works, but I want to learn to write elegant code. I'm trying my best. But I feel learn by example is the best.
kurt is offline   Reply With Quote
Old Feb 16th, 2008, 10:49 AM   #4
xavier
Professional Programmer
 
xavier's Avatar
 
Join Date: Oct 2004
Location: .ro
Posts: 406
Rep Power: 5 xavier is on a distinguished road
Send a message via Yahoo to xavier
Re: How to "expect an exception to occur" in the best code-style

how about throwing some code our way ? maybe we'll have better suggestions.
__________________
Don't take life too seriously, it's not permanent !
xavier is offline   Reply With Quote
Old Feb 16th, 2008, 10:56 AM   #5
mbd
Programmer
 
Join Date: Nov 2007
Posts: 86
Rep Power: 2 mbd is on a distinguished road
Re: How to "expect an exception to occur" in the best code-style

if this is a test method you should be using NUnit. are you? if so, on the test method you can place an attribute called ExpectedException. NUnit does the rest.
mbd is offline   Reply With Quote
Old Feb 16th, 2008, 5:44 PM   #6
kurt
Programmer
 
Join Date: Oct 2005
Posts: 72
Rep Power: 4 kurt is on a distinguished road
Re: How to "expect an exception to occur" in the best code-style

Quote:
Originally Posted by mbd View Post
if this is a test method you should be using NUnit. are you? if so, on the test method you can place an attribute called ExpectedException. NUnit does the rest.
Yes, indeed. I am using NUnit.

Initially I thought that [ExpectedException] just makes sure if that exception occurs, the test still passed. I didn't know it does check if the exception did not occur, the test fails -- this is what I wanted !!

Thanks for pointing out, else I would not have looked into the manual to check.

Thanks.
kurt is offline   Reply With Quote
Old Feb 16th, 2008, 5:49 PM   #7
kurt
Programmer
 
Join Date: Oct 2005
Posts: 72
Rep Power: 4 kurt is on a distinguished road
Re: How to "expect an exception to occur" in the best code-style

Quote:
Originally Posted by xavier View Post
how about throwing some code our way ? maybe we'll have better suggestions.
Although I get a clean elegant way with NUnit, I still would like to know how to write it better if the environment was not NUnit. So here's an example of my code

public void testAbort()
{
bool errorMissing = true;

try
{
   runner.Abort();  // This command must return expection!!
}
catch (SomeException e)
{
  errorMissing = false;
  Assert.AreEqual("Command obsolete", e.ErrorCode)
}
finally
{
  if (errorMissing)
        Assert.Fail();  // make the test fail
}
}
kurt is offline   Reply With Quote
Old Feb 17th, 2008, 12:08 AM   #8
xavier
Professional Programmer
 
xavier's Avatar
 
Join Date: Oct 2004
Location: .ro
Posts: 406
Rep Power: 5 xavier is on a distinguished road
Send a message via Yahoo to xavier
Re: How to "expect an exception to occur" in the best code-style

Well, you could use this from nunit : http://www.nunit.org/index.php?p=exception&r=2.4.3
in order to make the code smaller :

csharp Syntax (Toggle Plain Text)
  1. [ExpectedException(typeof(YourException))]
  2. public void testAbort()
  3. {
  4. runner.Abort(); // This command must return expection!!
  5. }
If the method does not throw, the test fails. However , you should be careful when using the ExpectedException attribute. It's ok for a one line test, but if you had several methods and another method would throw that exception, the test would still pass.

An improvement to that has been made in xUnit where you can do : Assert.Throws(method).
Best of luck.
__________________
Don't take life too seriously, it's not permanent !
xavier is offline   Reply With Quote
Old Feb 17th, 2008, 12:31 AM   #9
mbd
Programmer
 
Join Date: Nov 2007
Posts: 86
Rep Power: 2 mbd is on a distinguished road
Re: How to "expect an exception to occur" in the best code-style

beauty is in the eye of the beholder
mbd is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Incorporating javascript code into java application csrocker101 Java 1 Feb 11th, 2008 7:36 AM
Viewing VB's Automated code john Wesley Visual Basic .NET 3 Jun 8th, 2006 6:37 AM
FTP and return code fetching Serinth C 2 May 29th, 2006 12:05 AM
What Style Do You Program With? Darkhack Other Programming Languages 1 Feb 10th, 2006 3:07 AM
AhhH!!! I can't find anything on this exception... stakeknife ASP 2 Sep 26th, 2005 8:48 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 11:13 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC