I was wondering if the code below demonstrates a custom exception in C#?
public class NoBobException : Exception
{
public NoBobException()
: base("No Bob's in TextBox")
{
}
}
private void BobsForm_Load(object sender, EventArgs e)
{
if(textbox1.text == "Bob")
{
throw new NoBobException();
}
}
From this link : https://msdn.microsoft.com/en-us/library/87cdya3t(v=vs.110).aspx
I quote :
If you want users to be able to programmatically distinguish between some error conditions, you can create your own user-defined exceptions. The .NET Framework provides a hierarchy of exception classes ultimately derived from the base class Exception. Each of these classes defines a specific exception, so in many cases you only have to catch the exception. You can also create your own exception classes by deriving from the Exception class.
Conclusion : deriving from Exception is all it takes.
In the code example of this question, it is better to use an input data validation, because an exception handling in event handlers is complicated and it is better to avoid throwing exceptions in event handlers. The example of a custom exception is in my answer in a similar question Custom Exception C#.
Related
Microsoft's Best Practice says:
Introduce a new exception class only when a predefined one doesn't apply.
And:
When a custom exception is necessary, name it appropriately and derive it from the Exception class.
Deriving from the Exception class makes sense because that makes it possible for us to handle specific exceptions and (for example) log and throw the rest:
try
{
//something that might throw exceptions
}
catch(InvalidOperationException)
{
//Do something
}
catch(Exception ex)
{
//Log and throw other exception
throw;
}
I cant think of a reason why one would want to create an instances of the Exception base class. So why is Exception not marked as an abstract class?
I thought catching an abstract Exception might cause some special behaviour, but that does not seem to be the case:
public abstract class AbstractException : Exception
{
}
public class MyException : AbstractException
{
}
//...
try
{
throw new MyException();
}
catch (AbstractException)
{
//Works fine
}
Abstract classes are only required when there are abstract members. Exception doesn't have those so it doesn't require to be abstract.
But Microsoft could make it abstract to comply to their own best practices. Well, best practices are not set in stone, so a developer should have the choice to deviate from them. The non-abstract Exception provides that possibility.
There are lot of cases when you don't need any special or additional information to "describe" an exceptional situation in a computation flow. The Exception type is very suitable for such situations so that you don't have to define a new types for the generic exceptional situations. Being an abstract type the Exception wouldn't allow you to instantiate it and you'll have to invent some generic exception types from project to project in order to have an exception type "understandable" by all high-level consumers (that is provide a way to all consumers to catch and handle all exceptions regardless of an exception type specialization).
I've got the following code which retrieves a records details when I click on a table grid:
public ActionResult City(string rk)
{
try
{
var city = _cityService.Get("0001I", rk);
if (city == null)
{
throw new ServiceException("", "Error when fetching city " + rk);
}
}
}
What kind of exception should I use for this "no record found" problem? I see there are different kinds of exception, but I am not sure which would be appropriate or even if I am coding this correctly.
KeyNotFoundException would be a reasonable choice, and would conform to the Microsoft guideline to:
Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.
However you could consider creating your own Exception type if (again from the Microsoft guidelines):
... you have an error condition that can be programmatically handled in a different way than any other existing exceptions.
If you do create your own Exception, you should follow the guidelines for designing custom exceptions, e.g. you should make your Exception type Serializable.
You should create your own exception, and maybe call it RecordNotFoundException in this case.
Creating your own exception is quite easy. Just make a class, give it a name, extend Exception or some other exception type, and provide the constructors that you need (just calling the base Exception constructors).
If you want to add more, you can, but you often don't need to.
If you find yourself creating a number of exceptions for your project you may want to create a base exception type (that extends Exception) which all of your exceptions extend. This is something you might do when writing a library. It would allow someone to catch either a specific exception, or an exception thrown from your library, or any exception.
public class MySuperAwesomeException : Exception
{
public MySuperAwesomeException() : base() { }
public MySuperAwesomeException(string message) : base(message) { }
public MySuperAwesomeException(string message, Exception innerException)
: base(message, innerException) { }
}
I have decided to use Exceptions in my code to pass error handling around. I found myself duplicating code each time I wanted to create a new exception. These classes were nothing special and only contained a messaged. But I have come to rely on type safety when handing them. Is there a way to provide a new exception class type without having to re-implement the constructors?
[Serializable]
class MyNewException : MyBaseException
{
public MyNewException (String tMsg)
: base(tMsg)
{
}
public MyNewException (String tMsg, Exception tInnerEx)
: base(tMsg, tInnerEx)
{
}
}
The code above is duplicated many times over for each different type of exception I want to define.
Unfortunately, no, the constructors have to be provided since they are not inherited.
In addition, unless you are catching these specific exceptions and performing explicit processing when they occur, I would recommend having a generic exception that contains the additional information that you might need. However, this may not apply in your case.
The System.Exception class (actually any exception) has Data property which is almost always empty. While throwing exceptions, should this field be of any use? Or does it have some internal use that I am not aware of?
The documentation seems clear enough as to its use (emphasis added):
Gets a collection of key/value pairs that provide additional user-defined information about the exception.
Why does it exist in the first place? I assume it's the same reason Control has a Tag property. In the early days of .NET (before every Bob and Betty programmer understood objects and inheritance) they wanted to make the API simple enough that everyone could figure out how to add extra data to things.
However, the point of creating custom exceptions that derive from System.Exception is not necessarily to include additional information, but to make it possible for the client to limit the exceptions they catch to only those that they can handle. If they know how to handle a set of defined exceptions that your code can throw, they should be able to only catch those exceptions, without having to catch the base System.Exception class. What you should definitely never do is require the client code to catch a non-specific exception class and read a property to determine what type of exception it is (and thus whether or not they are able to handle it).
I've honestly never used this property before. I had to check the documentation to even see that it did indeed exist. But I imagine it's most useful for implementing custom exception logging. You can embed a lot of important information into the Data property (regardless of the level of derivation of exception class), and then pass that off to your logging code. Reflector indicates that it's used internally in a handful of places for precisely that purpose. It's also nice that all the information you provide here gets correctly serialized for you automatically.
Another note here, what I do when I inherit an exception and add properties, is to make the properties actually get and set from the data dictionary, and not from local variables.
[Serializable]
public class PacketParseException : Exception
{
public byte[] ByteData
{
get
{
return (byte[])this.Data["ByteData"];
}
}
public PacketParseException(string message, byte[] data, Exception inner) : base(message, inner)
{
this.Data.Add("ByteData", data);
}
}
The way I see it, then the internal data is available from an Exception as well, for example when logging, so no need to cast to actual type.
With the new CallerMemberNameAttribute it's even easier to use the Data property for storage:
public class BetterException : Exception
{
protected T GetValue<T>([CallerMemberNameAttribute] string propertyName = "")
{
return (T)Data[propertyName];
}
protected void SetValue<T>(T value, [CallerMemberNameAttribute] string propertyName = "")
{
Data[propertyName] = value;
}
}
Usage:
class MyException : BetterException
{
public MyException(string name)
{
Name = name;
}
public string Name
{
get { return GetValue<string>(); }
set { SetValue(value); }
}
}
In a follow-up to a previous question regarding exceptions, what are best practices for creating a custom exception in .NET?
More specifically should you inherit from System.Exception, System.ApplicationException or some other base exception?
In the C# IDE, type 'exception' and hit TAB. This will expand to get you started in writing a new exception type. There are comments withs links to some discussion of exception practices.
Personally, I'm a big fan of creating lots of small classes, at that extends to exception types. For example, in writing the Foo class, I can choose between:
throw new Exception("Bar happened in Foo");
throw new FooException("Bar happened");
throw new FooBarException();
where
class FooException : Exception
{
public FooException(string message) ...
}
and
class FooBarException : FooException
{
public FooBarException()
: base ("Bar happened")
{
}
}
I prefer the 3rd option, because I see it as being an OO solution.
Inherit from System.Exception. System.ApplicationException is useless and the design guidelines say "Do not throw or derive from System.ApplicationException."
See http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx
There is a code snippet for it. Use that. Plus, check your code analysis afterwards; the snippet leaves out one of the constructors you should implement.
I think the single most important thing to remember when dealing with exceptions at any level (making custom, throwing, catching) is that exceptions are only for exceptional conditions.
The base exception from where all other exceptions inherit from is System.Exception, and that is what you should inherit, unless of course you have a use for things like, say, default messages of a more specific exception.