Reason of not marking Exception as abstract - c#

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).

Related

Should custom exception classes derive from System.ApplicationException?

https://learn.microsoft.com/en-us/dotnet/api/system.applicationexception?view=net-5.0 says that "ApplicationException Class" Serves as the base class for application-defined exceptions. But in an example at https://learn.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-user-defined-exceptions custom exception class derives from "Exception" base class.
Well, MSDN states clearly
Important
You should derive custom exceptions from the Exception class rather
than the ApplicationException class. You should not throw an
ApplicationException exception in your code, and you should not catch
an ApplicationException exception unless you intend to re-throw the
original exception.
So for custom exception we should use Exception as a base class
Fundamentally, it doesn't matter. If your exception type would be a better logical fit when derived from one of the system-provided exceptions, as a user I'd prefer that kind of implementation. Think about what happens when user of your code catches the exceptions, and plan accordingly.

Custom Exception in C#

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#.

What kind of exception should I use for "No Record Found" ? (C#)

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) { }
}

Catching derived class exceptions from a catch specifying the base class

So I'll be honest, this is for a homework assignment. I know how to use try and catch, but I'm not quite sure what this question is asking, I'm not asking for the answer, just a clarification.
The Question:
Use inheritance to create an exception base class and various exception-derived classes. Write a program to demonstrate that the catch specifying the base class catches derived-class exceptions.
My basic train of thought is that I just make a new class called say.. "Exceptionz" and inherit from System.Exception, make several classes called say, "Derived 1", "Derived 2", then have each of those inherit from "Exceptionz". After that, I am not sure what the question is asking me to do.
Thanks for the help in advance!
It's asking you to create the exceptions as you suggested (Exceptionz as your base class, deriving from Exception, then two more classes, Derived1 and Derived2 that use Exceptionz as their base), then do something like this:
try
{
throw new Derived1();
}
catch (Exceptionz)
{
Console.WriteLine("Caught Derived 1");
}
try
{
throw new Derived2();
}
catch (Exceptionz)
{
Console.WriteLine("Caught Derived 2");
}
So you're showing that catching your base class (Exceptionz) also catches any of its derived exceptions (Derived1 and Derived2). Similar to how you may have an "I/O Exception" exception, then more specific ones deriving from it for permission denied, file not found etc.

What are some best practices for creating my own custom exception?

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.

Categories

Resources