This piece code works well, but if I want to use it in other programs, how can i do that?
Is it possible to create the exception like class library? If yes, how?
namespace Exception_CreatingUserDefined
{
public class FirstOperandSmallException : Exception
{
public FirstOperandSmallException(String message) : base (message)
{
}
}
public class operation
{
int op1, op2;
public void operatn()
{
if(op1 < op2)
{
throw (new FirstOperandSmallException("First Operand Should not be Small"));
}
else {
//Do nothing
}
}
}
class Test
{
static void Main(string[] args)
{
operation opr = new operation();
try
{
opr.operatn();
}
catch(FirstOperandSmallException e)
{
Console.WriteLine("FirstOperandSmallException : {0}",e.Message);
}
Console.Read();
}
}
}
As Kenny said, by simply including your namespace you are able to use any public classes you have defined inside it. To accomplish this, please do the following:
Make your exception class (and desired constructors) public.
Change the output type of this assembly to the 'Library' type. To do this, right click your project and go to Properties and set the output type as Library.
Also, common practice with Class Libraries is to remove your main (entrance) code, so it only has classes and methods.
I would ask why you need to create a Exception like this in the first place. You aren't adding any additional properties with your custom exception. If it was me I would just throw InvalidOperationException and not create a custom exception.
I would only create a custom exception if you have additional data you need to get into your Exception or if you have code that needs to specifically catch that exception. The framework has many built-in Exceptions you can use that cover a range of issues.
Related
I'm making my first "real" C# program and I'm thinking about where I should define error messages? Should I do something like this:
static class Error
{
public static string Example { get { return "Example Error"; } }
}
I could also use values here instead of properties but that would still mean I can't do something like this:
public static string FailedToParse(string filepath, string exmessage)
{
return ("Failed to parse " + filepath + ".\n" + exmessage);
}
So, is that a good idea? Should I make a new class and write a method for each error? How do you guys implement this and why?
I already read
In C#, what's the best way to store a group of constants that my program uses?
The right way to use Globals Constants
I think this is something everything should figure out by themselves.
One like to display nice messages to users another just throw those default generated ones.
Personally I like to have codes for errors.
Something like this:
I create a static class called ExceptionFactory and just pass the code to the method called RaiseException.
public static class ExceptionRegions
{
public static int Internet = 0xA;
public static int FileSystem = 0xB;
}
public class InternetConnectionException : Exception
{
public InternetConnectionException () : base("No internet connection available") { }
}
public class FileSystemAccessException : Exception
{
public FileSystemAccessException () : base("Access to specified path caused an error") { }
}
public static class ExceptionFactory
{
public static void RaiseException(int code)
{
switch(code)
{
case ExceptionRegions.Internet : throw new InternetConnectionException();
...
...
}
}
}
Btw, this is a well known pattern called Factory Pattern. :)
Why I like this, because it allows me to set regions in my application.
Usually an application has many interfaces such as file system, or web services, or database and all I need to do is create a code for each area and the factory will throw a nice message to user without exposing to the user name of database and number of code line or whatever the default generated error message looks alike.
I posted this question on the StoryQ discussion boards, but by looking at the (lack of) responses to other questions, activity there seems sparse at best. I thought I'd let everyone here have a go.
Is there a way to modify or configure the output (both output window and file) to include custom strings? For example, one of my stories requires that a specific exception is thrown. To do this, I catch the exception and save it, then in a separate method test that it's non-null and of the required type. I'd like to be able to append the type of the exception to the output (much like parameters are appended to method calls).
For example
.Then(ExceptionIsThrown<ArgumentNullException>)
would result in the following output
then exception is thrown (ArgumentNullException)
Thanks to Giorgio Minardi for guiding me to look into the StoryQ.Formatting namespace. There I discovered that I can override the method formatting using a simple attribute.
The API provides an OverrideMethodFormatAttribute (subclassed from the abstract class MethodFormatAttribute), which works if you want to use a specific string constant, but C# doesn't like the method's type parameters in attributes. This doesn't compile due to the T in the attribute:
[OverrideMethodFormat(string.Format("exception is thrown ({0})", typeof(T).Name))]
private void ExceptionIsThrown<T>() where T : Exception
{
...
}
The solution is to create another MethodFormatAttribute subclass that specifically searches the method for generic types and output them. This subclass is below:
public class GenericMethodFormatAttribute : MethodFormatAttribute
{
private readonly string _textFormat;
public GenericMethodFormatAttribute()
{
_textFormat = null;
}
public GenericMethodFormatAttribute(string textFormat)
{
_textFormat = textFormat;
}
public override string Format(MethodInfo method,
IEnumerable<string> parameters)
{
var generics = method.GetGenericArguments();
if (_textFormat == null)
{
var genericsList = string.Join<Type>(", ", generics);
return string.Format("{0} ({1})",
UnCamel(method.Name),
genericsList);
}
return string.Format(_textFormat, generics);
}
}
Usage is almost like the supplied attribute, except that you optionally supply a format string instead of a string constant. Omitting the format string un-camel-cases the method name just like the default behavior.
[GenericMethodFormatAttribute]
private void ExceptionIsThrown<T>() where T : Exception
{
...
}
This allows me to declare the attribute in my source, while not having to touch the StoryQ code. Ten points to StoryQ for extensibility!
Best thing is to look at the sources of StoryQ, in particular look at the StoryQ.Formatting namespace. To get a particular output you should follow the FluenInterface pattern used within the framework and wrote your own method, something like ThenExceptionIsThrown(Exception ex) and chain it like the other methods in the story.
Hi I have a possible design flaw and i need to solve it with an extension method.
Lets say I have a class and it has a property of StringCollection. Example code
public class MyProblematicClass
{
public IDbAccess Db{get;set;}
public StringCollection Errors{get;set;}
public MyProblematicClass(IDbAcces db){ Db=db;}
public int SetItem(Item i)
{
var id = Db.Save(i);
this.Errors = Db.Erros;
return id;
}
}
What I am doing is, in my unit test class I mock IDbAccess. This class validates object according to attributes. If any error occures it doesnt hit to db, it just fills its own Errors collection. For unit test I use another dbclass which just runs validation routines and here is problem i cannot get Error. Let me give you example for further understanding ( I know design is problematic, but for now I want to deal with it without changing anything)
public static class MyDbExtension
{
public static Save(Item i)
{
Validation v = new Validation();
var erros = v.ValidateObject(i);
//Here is problem i cannot pass it to MyProblematicClass
if ( errors.Count > 0 )
return -1;
else
return 1;
/* what I want to is :
var stackTrace = new StackTrace(); get stack trace
var object = stackTrace.GetFrame(1).GetMethod().GetObject() or sth like that. get object
object.GetProperties()[0].SetValue(object,errors,null); find property and set it.
*/
}
}
in my unit test :
public class UnitTest
{
Mock<IDbAccess> _db ;
MyProblematicClass _mpc;
pubic Setup()
{
_db.Setup(x=>x.Save(It.IsAny<Item>).Returns(u =>MyDbExtension.Save(u));
_mpc = new MyProblematicClass(_db.Object);
}
public void SetItem_EmptyObject_Contains3Erros()
{
Item i = new Item();
_mpc.SetItem(i);
//At this point i cannot set _mpc.Errors
}
What I want to achieve is in my DbExtension class can I access caller class and set its Errors property? I tried but it wasn unlikely yet. If anyone has any decent solution I will be appreciative and of course you can comment on design problems.
Edit
I appreciate Alex's answer he just said ignore Save method just mock Erros property and it will be ok. That make sense but what I wonder is in question, is it possible to access Stack Trace and manipulate caller methods object's property?
Thanks in advance.
You need to setup the return value of _db.Errors, something like this:
public class UnitTest
{
Mock<IDbAccess> _db ;
MyProblematicClass _mpc;
StringCollection errors;
pubic Setup()
{
_db.Setup(x=>x.Save(It.IsAny<Item>).Returns(u =>MyDbExtension.Save(u));
_db.Setup(x=>x.Errors).Returns(errors);
_mpc = new MyProblematicClass(_db.Object);
}
public void SetItem_EmptyObject_ContainsError()
{
errors.Add("Expected Error!");
Item i = new Item();
_mpc.SetItem(i);
Assert.AreEqual("Expected Error!", _mpc.Errors[0]);
}
}
I must admit I don't really follow your design, why are you using a static method for save? You could just as easily have the line:
_db.Setup(x=>x.Save(It.IsAny<Item>).Returns(-1);
Then test IDbAccess.Save() independently.
In your 'extension' class the save method has no return value, and MyProblematicClass does not inspect the return value before assigning errors.
Not sure to fully understand the question, but you cannot access the parameters on the stack from a normal program. Runtime metadata is only about static information (method, properties, constants, etc...).
I believe only a debugger (which is considered as a special beast of its own) can do this without changing the program/source, and this has serious performance cost. As a side note, here is a link that explain how to build your own managed debugger (.NET 4): CLR Managed Debugger (mdbg) Sample 4.0
Another solution is to instrument your code (automatically or using a tool) to add some tracing call that can capture the list of parameters on each traced methods. Tools like PostSharp can do this. Here is another link: Non-Invasive Tracing & Logging
You could use unmanaged debugging API to access the call stack and get the object previous function on the stack was called on.
The problem is, the stack may not contain the method you are expecting. In cases such as inlining and tail call optimization, the call stack doesn't contain the previous method called, which means you can't reliably do what you want.
For more information see this answer by Eric Lippert.
This doesn't use the call stack, but might get you some mileage:
class CalledClass
{
public static void PokeCaller()
{
Program._this.Error = "Error!!!";
}
}
class Program
{
public string Error = null;
[ThreadStatic] public static Program _this;
public void Run()
{
_this = this;
CalledClass.PokeCaller();
Console.WriteLine(Error);
Console.ReadKey();
}
static void Main(string[] args)
{
Program p = new Program();
p.Run();
}
}
Making Errors be [ThreadStatic] might be a more direct way to do it... or some other variation on that theme. You might also combine it with stack trace checking to see if you were actually called by something that has "Errors" attribute before setting it...
I ran across a pattern in a codebase I'm working on today that initially seemed extremely clever, then later drove me insane, and now I'm wondering if there's a way to rescue the clever part while minimizing the insanity.
We have a bunch of objects that implement IContractObject, and a class InvariantChecker that looks like this:
internal class InvariantChecker : IDisposable
{
private IContractObject obj;
public InvariantChecker(IContractObject obj)
{
this.obj = obj;
}
public void Dispose()
{
if (!obj.CheckInvariants())
{
throw new ContractViolatedException();
}
}
}
internal class Foo : IContractObject
{
private int DoWork()
{
using (new InvariantChecker(this))
{
// do some stuff
}
// when the Dispose() method is called here, we'll throw if the work we
// did invalidated our state somehow
}
}
This is used to provide a relatively painless runtime validation of state consistency. I didn't write this, but it initially seemed like a pretty cool idea.
However, the problem arises if Foo.DoWork throws an exception. When the exception is thrown, it's likely that we're in an inconsistent state, which means that the InvariantChecker also throws, hiding the original exception. This may happen several times as the exception propagates up the call stack, with an InvariantChecker at each frame hiding the exception from the frame below. In order to diagnose the problem, I had to disable the throw in the InvariantChecker, and only then could I see the original exception.
This is obviously terrible. However, is there any way to rescue the cleverness of the original idea without getting the awful exception-hiding behavior?
I don't like the idea of overloading the meaning of using in this way. Why not have a static method which takes a delegate type instead? So you'd write:
InvariantChecker.Check(this, () =>
{
// do some stuff
});
Or even better, just make it an extension method:
this.CheckInvariantActions(() =>
{
// do some stuff
});
(Note that the "this" part is needed in order to get the C# compiler to look for extension methods that are applicable to this.) This also allows you to use a "normal" method to implement the action, if you want, and use a method group conversion to create a delegate for it. You might also want to allow it to return a value if you would sometimes want to return from the body.
Now CheckInvariantActions can use something like:
action();
if (!target.CheckInvariants())
{
throw new ContractViolatedException();
}
I would also suggest that CheckInvariants should probably throw the exception directly, rather than just returning bool - that way the exception can give information about which invariant was violated.
This is a horrid abuse of the using pattern. The using pattern is for disposing of unmanaged resources, not for "clever" tricks like this. I suggest just writing straight forward code.
If you really want to do this:
internal class InvariantChecker : IDisposable
{
private IContractObject obj;
public InvariantChecker(IContractObject obj)
{
this.obj = obj;
}
public void Dispose()
{
if (Marshal.GetExceptionCode() != 0xCCCCCCCC && obj.CheckInvariants())
{
throw new ContractViolatedException();
}
}
}
Instead of this:
using (new InvariantChecker(this)) {
// do some stuff
}
Just do this (assuming you don't return from do some stuff):
// do some stuff
this.EnforceInvariants();
If you need to return from do some stuff, I believe some refactoring is in order:
DoSomeStuff(); // returns void
this.EnforceInvariants();
...
var result = DoSomeStuff(); // returns non-void
this.EnforceInvariants();
return result;
It's simpler and you won't have the problems you were having before.
You just need a simple extension method:
public static class InvariantEnforcer {
public static void EnforceInvariants(this IContractObject obj) {
if (!obj.CheckInvariants()) {
throw new ContractViolatedException();
}
}
}
Add a property to the InvariantChecker class that allows you to suppress the check/throw.
internal class InvariantChecker : IDisposable
{
private IContractObject obj;
public InvariantChecker(IContractObject obj)
{
this.obj = obj;
}
public bool Suppress { get; set; }
public void Dispose()
{
if (!this.Suppress)
{
if (!obj.CheckInvariants())
{
throw new ContractViolatedException();
}
}
}
}
internal class Foo : IContractObject
{
private int DoWork()
{
using (var checker = new InvariantChecker(this))
{
try
{
// do some stuff
}
catch
{
checker.Suppress = true;
throw;
}
}
}
}
If you current problem is to get original exception - go to Debug -> Exceptions and check "thrown" for all CLR exceptions. It will break when exception is thrown and as result you'll see it first. You may need to also turn off tools->options->debug->"my code only" option if exceptions are throw from "not your code" from VS point of view.
What is needed to make this nice is a clean means of finding out whether an exception is pending when Dispose is called. Either Microsoft should provide a standardized means of finding out at any time what exception (if any) will be pending when the current try-finally block exits, or Microsoft should support an extended Dispose interface (perhaps DisposeEx, which would inherit Dispose) which would accept a pending-exception parameter.
Let's say we have the following piece of code:
public class Event { }
public class SportEvent1 : Event { }
public class SportEvent2 : Event { }
public class MedicalEvent1 : Event { }
public class MedicalEvent2 : Event { }
public interface IEventFactory
{
bool AcceptsInputString(string inputString);
Event CreateEvent(string inputString);
}
public class EventFactory
{
private List<IEventFactory> factories = new List<IEventFactory>();
public void AddFactory(IEventFactory factory)
{
factories.Add(factory);
}
//I don't see a point in defining a RemoveFactory() so I won't.
public Event CreateEvent(string inputString)
{
try
{
//iterate through all factories. If one and only one of them accepts
//the string, generate the event. Otherwise, throw an exception.
return factories.Single(factory => factory.AcceptsInputString(inputString)).CreateEvent(inputString);
}
catch (InvalidOperationException e)
{
throw new InvalidOperationException("Either there was no valid factory avaliable or there was more than one for the specified kind of Event.", e);
}
}
}
public class SportEvent1Factory : IEventFactory
{
public bool AcceptsInputString(string inputString)
{
return inputString.StartsWith("SportEvent1");
}
public Event CreateEvent(string inputString)
{
return new SportEvent1();
}
}
public class MedicalEvent1Factory : IEventFactory
{
public bool AcceptsInputString(string inputString)
{
return inputString.StartsWith("MedicalEvent1");
}
public Event CreateEvent(string inputString)
{
return new MedicalEvent1();
}
}
And here is the code that runs it:
static void Main(string[] args)
{
EventFactory medicalEventFactory = new EventFactory();
medicalEventFactory.AddFactory(new MedicalEvent1Factory());
medicalEventFactory.AddFactory(new MedicalEvent2Factory());
EventFactory sportsEventFactory = new EventFactory();
sportsEventFactory.AddFactory(new SportEvent1Factory());
sportsEventFactory.AddFactory(new SportEvent2Factory());
}
I have a couple of questions:
Instead of having to add factories
here in the main method of my
application, should I try to
redesign my EventFactory class so it
is an abstract factory? It'd be
better if I had a way of not having
to manually add
EventFactories every time I want to
use them. So I could just instantiate MedicalFactory and SportsFactory. Should I make a Factory of factories? Maybe that'd be over-engineering?
As you have probably noticed, I am using a inputString string as argument to feed the factories. I have an application that lets the user create his own events but also to load/save them from text files. Later, I might want to add other kinds of files, XML, sql connections, whatever. The only way I can think of that would allow me to make this work is having an internal format (I choose a string, as it's easy to understand). How would you make this? I assume this is a recurrent situation, probably most of you know of any other more intelligent approach to this. I am then only looping in the EventFactory for all the factories in its list to check if any of them accepts the input string. If one does, then it asks it to generate the Event.
If you find there is something wrong or awkward with the method I'm using to make this happen, I'd be happy to hear about different implementations. Thanks!
PS: Although I don't show it in here, all the different kind of events have different properties, so I have to generate them with different arguments (SportEvent1 might have SportName and Duration properties, that have to be put in the inputString as argument).
I am not sure about the input string question but for the first question you can likely use "convention over configuration"; a combination of reflection, the IEventFActory type and the naming you already have in place, Name.EndsWith("EventFactory") should allow you to instantiate the factories and get them into their Lists with code.
HTH ,
Berryl