I am recently assigned a task to extend an existing WPF (C# .Net) application for an error handler. The handler is supposed to display a friendly message with possible easy solution for the user. It is required that I change nearly no code = I can only work in App.xaml.cs code behind. My approach is to try to identify the error from the stack trace and from the properties of the innermost exception. So far, I am using these three identifiers:
string identifierMethod= new System.Diagnostics.StackTrace(ex.GetBaseException()).GetFrame(0).GetMethod().Name;
string identifierObject = ex.GetBaseException().TargetSite.ReflectedType.FullName;
string identifierHResult = ex.GetBaseException().HResult.ToString();
//ex is the uppermost exception coming to App
I need to identify the root method and object where the exception originated. Combining these three seems to work for me but I don’t think it is very clean and robust and I fear there could be some exception that will have duplicate combination of these three identifiers. Sometimes the innermost exception’s stack trace is null, sometimes it seems to me the identifiers do not really describe the lowermost method or object constructor which caused the Exception.
I know I could ideally use Exception Data or Source properties assigning some identifiers in try catch block where the Exception originate but I simply cannot. I know similar question were asked but they only gave me what I have now.
Thanks a lot for any suggestions and ideas.
You can use Checked Exceptions to announce the caller methods about the callees' exceptions. And in caller methods, you can easily handle the exception by their types, identify the exception origin, and have a friendly message.
To add the Checked Exception feature into the C#, you can use this nugget package: Portia.Roslyn.CheckedException.
Suppose I write some multi-threaded C# code. (I know ... bad idea from the get-go ;) )
I have some code B, which I expect to only get called after code A has completed. I write and review my code carefully to convince myself that this is true, but I can't actually enforce that expectation, I can only check whether it is true.
So I put the checks in, and if the check ever fails, I want to throw and exception so that the developer gets a big shouty log message saying "Nope, ya fucked up; there's still an edge case where the threading doesn't do what you'd convinced yourself it did."
What's the best C# Exception type to throw here?
My instinct is to go with that old stand-by InvalidOperationException or possibly just a raw new Exception(message). But it would be nice if there were a slightly more specific type I could throw (like throwing an ArgumentException when that's the issue that's happened)
There are a few Exception types that auto-complete from Thread or Sync but they all look like they're intended for much deeper problems. i.e. there's something wrong with the actual threads. Here the thread are all fine ... it's the developer's threading logic that's in error.
Are there any sensible pre-existing Exception classes to use here?
An InvalidOperationException is the most suitable built in exception for this situation.
See it's official documentation remarks section:
InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it is thrown when the state of an object cannot support the method call.
(emphasis mine).
Of course, there's nothing stopping you from creating your own Exception class if you want something more specific, but that would only make sense if you want the exception to carry information that doesn't fit inside the InvalidOperationException (and of course, if you do choose to create your own exception class, be sure to follow the guidlines in How to create user-defined exceptions:
Derive from an existing Exception class
use the word Exception as a suffix to the class name (MyVeryOwnSpecialException)
Implement at least three public constructors:
3.a: A constructor with no parameters
3.b: A constructor that takes in a string message
3.c: A constructor that takes in a string message and an Exception inner exception.
if you think there is a possibility of getting a null pointer exception, should you use an if statement to make sure the variable is not null, or should you just catch the exception?
I don't see any difference as you can put your logic to deal with the null pointer in the if statement, or in the catch block, so which one is best practise?
I would say ALWAYS use logic to catch the exception, not try/catch.
Try/Catch should be used when you validate but some strange thing happens and something causes an error so you can handle it more gracefully.
There is no single answer that will suffice here, it depends.
Let's take a few scenarios so you can see what I mean.
Scenario: Method that takes a reference type parameter that does not accept null
You're defining a method, it takes a reference type parameter, say a stream object, and you don't want to accept null as a legal input parameter.
In this case, I would say that the contract is that null is not a valid input. If some code does in fact call that method with a null reference, the contract is broken.
This is an exception, more specifically, it's an ArgumentNullException.
Example:
public void Write(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
...
I would definitely not just let the code execute until it tries to dereference the stream in this case, instead crashing with a NullReferenceException, because at that point I lost all ability to react when I know the cause.
Q. Why can't I return false instead of throwing an exception?
A. Because a return value is easy to silently ignore, do you really want your "Write" methods to just silently skip writing because you made a snafu in the calling code, passing the wrong stream object or something that cannot be written to? I wouldn't!
Scenario: Method returns a reference to an object, sometimes there is no object
In this case the contract is that null is a legal result. In my opinion, null is something to avoid because it is quite hard to make sure you handle correctly everywhere, but sometimes it is the best way.
In this case I would make sure to if my way around the result, to ensure I don't crash when the null reference comes back.
Generalisation
If you take a close look at the above two scenarios, you'll note one thing:
In both cases it comes down to what is being expected, what the contract is.
If the contract says "not null", throw an exception. Don't fall back to the old-style API way of returning false because an exceptional problem should not be silently ignored, and littering the code with if statements to ensure every method call succeeds does not make for readable code.
If the contract says "null is entirely possible", handle it with if statements.
Advertising
For getting a better grip on null problems, I would also urge you to get ReSharper for you and your team, but please note that this answer can be applied to any type of exception and error handling, the same principles applies.
With it comes attributes you can embed into your project(s) to flag these cases, and then ReSharper will highlight the code in question.
public void Write([NotNull] Stream stream)
[CanBeNull]
public SomeObject GetSomeObject()
To read more about the contract attributes that ReSharper uses, see
ReSharper NullReferenceException Analysis and Its Contracts
Contract Annotations in ReSharper 7
Well. Exceptions are just that. Exceptions. They are thrown when something unforseen has happened and should not be part of the normal program flow.
And that's what is happening here. You expected the argument to be specified when it's not. That is unexpected and you should therefore throw your own exception informing the user of that. If you want to get bonus points you can also include the reason to WHY the argument must be specified (if it's not obvious).
I've written a series of posts about exceptions: http://blog.gauffin.org/2013/04/what-is-exceptions/
From a performance standpoint it really depends what you're doing. The performance impact from a try/catch block when no exception is thrown is minimal (and if you really need that last few percent of performance, you probably should rewrite that part of your code in C++ anyway). Throwing exceptions does have a major impact on simpler operations such as string manipulation; but once you get file/database operations in the loop they're so much slower that again it becomes a trivial penalty. Throwing across an App Domain will have a non-trivial impact on just about anything though.
Performance in Operations/second:
Mode/operation Empty String File Database Complex
No exception 17,748,206 267,300 2,461 877 239
Catch without exception 15,415,757 261,456 2,476 871 236
Throw 103,456 68,952 2,236 864 236
Rethrow original 53,481 41,889 2,324 852 230
Throw across AppDomain 3,073 2,942 930 574 160
Additional test results along with the source for the tests is available from the article Performance implications of Exceptions in .NET
I would rather suggest you use if-statement for NullReference exception. For other exception, try-catch should be good enough.
The reason I suggest if-statement for NullReference exception is because C# will not tell which variable is null. if that line has more than one object could be null, you will loss track. If you are using if-statement, you can have better logging to help you get the enough information.
The main Question is if it is a good idea to have methods returning Null at all, personally i do not have any problem with this, but as soon as you try to access modifiers of an object returned from this method and you forget to check if it is assigned this becomes an issue.
Ken has a good answer about this:
If you are always expecting to find a value then throw the exception
if it is missing. The exception would mean that there was a problem.
If the value can be missing or present and both are valid for the
application logic then return a null.
See this disscussion abou tthis issue:
Returning null is usually the best idea if you intend to indicate that
no data is available.
An empty object implies data has been returned, whereas returning null
clearly indicates that nothing has been returned.
Additionally, returning a null will result in a null exception if you
attempt to access members in the object, which can be useful for
highlighting buggy code - attempting to access a member of nothing
makes no sense. Accessing members of an empty object will not fail
meaning bugs can go undiscovered.
Some further reading:
No Null Beyond Method Scope
Should We Return Null From Our Methods?
using try catch for the statements is not an good idea. because when you use try catch them it seems that if some error comes the code will not turninate the application. but if you are sure about what kind of error can come you can tap the error at that point. that will not produce any unknown errors. for example.
string name = null;
here i am going to use the name variable and i am sure that this will throw Null Refrance Error .
try
{
Console.writeLine("Name ={0}",name);
}
catch (NullRefranceException nex)
{
//handle the error
}
catch(Exception ex)
{
// handle error to prevent application being crashed.
}
This is not a good practice while you can handle this kind of error and make your code more readable. like.
if(name !=null)
Console.writeLine("Name ={0}",name);
In my experience using if is better but only if you actually expect a null reference pointer. Without any bit of code or context its difficult to say when one option is better than the other.
There's also a matter of optimization - code in try-catch blocks won't be optimized.
In general, try-catch blocks are great because they will break (move to the catch statement) whenever the exception occurs. If-else blocks rely on you predicting when the error will happen.
Also, catch blocks won't stop your code from halting when an error is hit.
Its always better to use Try Catch other than if else
Here Exceptions are two types namely handled and UN-handled exceptions
Even if u want to handle some function when the Exception u can handle it...
Handled exception always allows you to write some implementations inside the Catch block
Eg. An Alert Message, A new Function to handle when such exception occurs.
Is there anything like exception code? that i can know that on different languages operation system i can recognize the same exception?
I need to recognize 'Acces to the COMn Port is denied' and then do some action, is that possible? has this exception any specified type?
From the sounds of it you will be getting a System.UnauthorizedAccessException (this assumption has been made from Googling the error message and finding this forum). To handle this, you would need to use catch clauses in a try-catch statement that are specific to this exception type. So, in C# you would do something like:
try
{
// ... Run some code that might cause the error in question ...
}
catch (System.UnauthorizedAccessException ex)
{
// ... Run some code that handles the error in question ...
}
There is no concept of a global exception code in .NET -- and there really could never be, since it implies that every author of every exception class on the planet would have to collaborate in order to choose codes.
You also cannot assume that a particular message signals an exception of a particular type, since the message can (in the general case) be freely chosen at the throw site.
You could do a type switch on exception.GetType() to find what the runtime type of an exception is, but that is not guaranteed to be a solution (it depends on what was actually thrown, which could be a vanilla System.Exception for all we know).
What exactly are you trying to achieve?
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Create custom exception or use built-in exceptions?
Hi,
In program design, is it normal to model exceptions for business constraints? E.g. if xyz must be >1 in order to get abc (a basket object must exist before being able to add objects), and the basket does not exist, is this a good enough reason to have a custom exception to model this real-world scenario?
What reasons contribute to using custom exceptions?
I think the question is not whether one should create a custom exception class, but whether one should use exception for normal conditions of incorrect input, i.e. if you ask a user to create a new password, should the code internally throw PasswordTooWeakException (or InvalidArgumentException) when the password is too weak, or should handle it in another way.
If that is the question, my answer is no, you should not use exceptions in this case. Exceptions are for exceptional cases only, i.e. error situations, where something not expected happens.
If the basket does not exist, sounds like a ArgumentNullException or an InvalidOperationException depending whether the variable is a parameter or not. If xyz must be greater than 1, sounds like an ArgumentException. The latter case also sounds like something you could handle without resorting to exceptions depending upon where the validation is taking place.
There are many of already defined exceptions as part of the standard library. My advice is to rely upon those until you can clearly demonstrate that such exceptions truly do not cover your particular scenario.
I use custom exceptions when I plan on treating them differently (or think they should be treated differently). For many situations, the general exceptions with a good message are good enough.
If all you plan on doing in the catch is display the message, then you don't get much out of custom exceptions.
Most of the time, I would recommend an exception that already exists. Like #Anthony says with the ArgumentException. You can always leave a message inside the Exception if you want.
Sometimes, it is handy to have your custom exceptions. For example when you have such code:
catch(ArgumentException e)
{
if(e.Message.Equals("The argument was bigger than 0"))
// do something
else
// do something else
}
That would result in messy code and maybe a custom event or wrapper exception would be more appropriate.
Maybe you could check this blog as well: http://blogs.msdn.com/b/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx
It sounds like you are attempting to create exceptions that duplicate the functionality of existing exceptions. For example, your empty basket scenario could be handled by throw new ArgumentException("Basket not instantiated");
When in doubt, fall back to the Exception Design Guidelines on MSDN.