Should custom exceptions be used when only a message is involved? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have seen many cases where custom exceptions where created, where only the 3 standard constructor overrides are used with no extra information to it.
In those cases I recommended to use InvalidOperationException because in practice there were no callers that catch those custom exceptions.
For example for use in a default block in a switch statement:
public InvalidSwitchValueException()
: base() { }
public InvalidSwitchValueException(string message)
: base(message) { }
public InvalidSwitchValueException(string message, Exception innerException)
: base(message, innerException) { }
What would you recommend ?

Depends. If you intend to use it like this:
try
{
}
catch (InvalidSwitchValueException)
{
// handle this special case differently
}
catch (Exception)
{
}
It is much neater than:
try
{
}
catch (Exception e)
{
if (e.Message == "Check the message")
{
// handle this special case differently
}
}
If it is just to have a different type, with no intend to catch it anywhere, it don't see the point. If you do, it will improve your code quality. Think what happens if you have multilingual error messages (like .NET itself does). You can't and shouldn't rely on the message! Never!
Eric Lippert makes a good point in comment too:
Is this an exception that should never be caught because it indicates a bug in the caller that should be fixed? If so then design the exception to make the bug easy to find and fix, rather than designing the exception to be easy to catch.
A very useful point in naming exceptions is that if they are thrown, it's easier to find them. As an example: NullReferenceException is the worst to get since (without the call stack) it absolutely gives you nothing to help analyze the problem. A check and throw of a typed exception like CatDidntFindMouseException gives you a starting point and probably a clue what is actually going wrong.

Related

What's the best practice to structure exception messages? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
When something goes wrong in your program, you can throw an exception in your code with a message that describes a problem. Typical example:
throw new Exception("Houston we have a problem");
Is it a good practice to pass a hardcoded string into an exception constructor? Maybe I should hold all of exception messages in a one place. Please tell me what's the best practice to solve a problem of exception message structuring.
As Tim mentioned in the comments already localization can be a problem if the messages are shown to users.
What my approach on this topic is, and what I really like to suggest is the following.
Try to make it generic.
Makea a constants class holding your exception Messages with meaningfull constants names like this:
public static const String IN_VARIABLE_MISSING = "An expected value is missing. Please try again";
This will give you the ability to actually re-use the exception wherever it is needed. ( Also you only need to edit it at one place and have it updated everywhere ) You can build a wrapper which will handle the localization. But there are so many options for that topic, that I will not elaborate too much.
So you then can throw an exception like this:
throw new Exception(IN_VARIABLE_MISSING);
If this is software which will be used commercial I would also recommend to write an own Exception which extends the standard Exception.
Why?
You can create an exception that will take your message and an number for example and will automatically build an unique key for you like this:
IN-MODULE-NUMBER-IDENTIFICATION
You see where that could be handy? Excactly in localization and in faster finding of where it happened and why it happened.
You can modify it to write IN at the beginning for Internal errors. VA for validation errors. Then the class/project where it happened and then a number or whatever you want.
This system will also give you the ability to use another string for that key depending on the locale the user is using.
TL;DR Make it reusable!
Is it a good practice to pass a hardcoded string into an exception constructor?
Yes and No.
No in the sense that this code:
throw new Exception("Houston we have a problem");
is much harder for the caller to deal with. That's because what the exception means is identified only by the text of the message; therefore a caller wanting to catch exceptions from your code (for example, so as not to crash but continue running if possible) has to make string comparisons to figure out what the problem was.
e.g.
try
{
someService.DoSomething(sessionId)
}
catch(Exception ex)
{
if (ex.Message.Contains("Houston"))
{
//this indicates that someService couldn't connect to the database
}
else if(ex.Message.Contains("is on fire"))
{
//someService detected that the network is exploded
}
else{
//we can only handle the two previous cases, all else is passed on}
throw;
}
As you can see this gets messy fast, and if someone changes the text....
Now this code, on the other hand:
throw new SomethingSpecificWentWrongException(sessionId);
where SomethingSpecificWentWrongException might look like this:
public class SomethingSpecificWentWrongException: Exception
{
public int SessionId {get;protected set;}
public SomethingSpecificWentWrongException(int sessionId):
base($"Something specific went horribly wrong with session {sessionId}")
{
SessionId=sessionId;
}
}
can easily be handled by the caller:
try
{
someService.DoSomething(sessionId)
}
catch(SomethingSpecificWentWrongException ex)
{
//do whatever it is you do to recover from this
}
catch(SomethingElseSpecificWentWrongException wex)
{
//recover from this
}
else
{
throw;
}
You'll notice that there is a hard-coded-ish string here but it's owned by the custom exception class itself, not by the code that decides to throw the exception; this makes a big difference because it means you can guarantee that wherever this exception is used the message is predictable (in terms of logging, etc).
So not only is it easier to reason about, it's a lot more maintainable than hard-coding strings provided by the throwing code.

can we Throwing Exception to a specific method c#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I've cascading drop downs in my c# winform application and i'm getting data from wcf service and filling the drop downs. I want if any exception occurs in my event handlers then i should be able to throw exception to a specified method.
Is that Possible? Any syntax for this?
something like this
MethodName(throw);
No, you can't throw an exception to a specific method. The exception always bubbles up the call stack.
You can handle an exception by calling another method. In that case, just pass the exception to it:
try
{
}
catch (Exception ex)
{
ShowErrorToUser(ex);
}
private void ShowErrorToUser(Exception ex)
{
MessageBox.Show(ex.Message);
}
There is no built-in way to do this. Exceptions are raised and (simplified) bubbling up the call stack. So it always has to be a method in the call hierarchy that catches the exception.
You will need to add a call to the method that should handle the exception in your catch blocks.

C# - How to structure error handling in code properly [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am fairly new to programming and I want to know what is the proper way to structure your error handling. I have searched the internet but I have failed to find something solid about the structure of ALL your try/catch/finally statements, and how they interact with each other.
I want to present my idea of how I think I should structure my error handling in code and I would like to invite everyone check if this is correct. A big bonus would be to back it up with some other research, a common practice of some sort.
So my way of doing this would be to put try statements pretty much everywhere! (I hope I haven't raged everyone by saying this). PS - I also understand about catching different types of exceptions, I am only catching of type 'Exception' just for explanation purposes.
So for example:
I start on Main in a normal console application and then I create an
instance of A.
I then call a member function on it called AMethod1 (a.AMethod1).
A.AMethod1 creates an instance of class B and then calls BMethod1
(b.BMethod1).
This is how I would go about error handling it:
public class Program
{
static void Main (string[] args)
{
//I do not place simple code like below inside the try statement,
//because it is unnecessary and will slow the process down.
//Is this correct?
const int importantNumber = 45;
string name;
IRepositoryFactory repoFactory;
A a;
//And then I put code in 'try' where I feel it may go wrong.
try
{
a = new A();
a.AMethod1();
//Some other code
}
catch (Exception ex)
{
HandleError(ex);
}
}
}
// End of scope of Program! The functions below belong to their relative
// classes.
public void AMethod1()
{
try
{
B b = new B();
b.BMethod1();
}
catch (Exception ex)
{
//Preserving the original exception and giving more detailed feedback.
//Is this correct?
//Alternative - you still could do a normal 'throw' like in BMethod1.
throw new Exception("Something failed", ex);
}
}
public void BMethod1()
{
try
{
//some code
}
catch (Exception ex)
{
throw; //So I don't lose stack trace - Is this correct?
}
}
In summary:
I put all code in try statements (except declarations like shown in
above code)
On the client level (at the start of the call stack) I
catch the error and handle it.
Going down the call stack, I just
throw the Exception so I don't break the stack information.
I would really appreciate some resources that explains how programmers are meant to structure their error handling. Please don't forget to read the comments within the code please.
Here are some good rules of thumb:
If you are going to log the error at the level in question, use exception handling
If there is some way to solve the exception, use exception handling
Otherwise, don't add any exception handling at that level
The exception to the rules above is the UI should ALWAYS (okay, maybe not always, but I can't think of an exception to this rule right off hand) have exception handling.
In general, if you are throwing the same error, as you have in your code, it is a sign you should not handle the exception. End of story.
NOTE: When I say "at that level", I mean in the individual class or method. Unless the exception handling is adding value, don't include it. It always adds value at the user interface level, as a user does not have to see your dirty laundry, a message saying "oops, laundry day" is enough.
In my personal experience most of the exceptions are related to null object reference. I tend to follow null object pattern to avoid lots of check for null values. And also while doing a value conversion I always use tryparse so that i dont stand a chance of null issues. all in all this subject could be discussed from many perspective. if you could be a bit more specific it will be easy to answer.
stackoverflow really isn't an opinion site. It's geared heavily towards specific answers to specific questions.
But you should know that try...catch does have some overhead associated with it. Putting it "everywhere" will hurt the performance of your code.
Just use it to wrap code that is subject to unexpected errors, such as writing to disk, for example.
Also note that the "correct" way depends on what you are doing with those errors. Are you logging them, reporting them to the user, propagating them to the caller? It just depends.

Correct way to document bubbled exceptions in C#? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Below is a simplified example of a setup I have. My issue is an exception is thrown at a low level which will then bubble up. However, classes at a higher level do not know what horrors await them when they use the lower level class functions. By this I mean developers will come along and use Class3.DoWork3() without any exception handling for the dreaded 'MyCustomException'.
Am I approaching this all wrong? I don't want to catch and throw the same exception multiple times (I have no need to do any kind of clean up for example in Class2).
public class Class1
{
<exception cref="MyCustomException">description</exception>
public void DoWork1()
{
throw new MyCustomException("I have failed you class1.");
}
}
public class Class2
{
public void DoWork2()
{
var classOne = new Class1();
// Here I can see that DoWork1() will throw a 'MyCustomException'
classOne.DoWork1();
}
}
public class Class3
{
public void DoWork3()
{
var classTwo = new Class2();
// I can no longer see that Class2.DoWork2() will throw a 'MyCustomException'
classTwo.DoWork2();
}
}
In order to clear up some confusion which seems to have been generated in the comments I will put the two solutions which I am considering at present:
Tag DoWork2 with the same MyCustomException comment as Class1
Throw a different exception within DoWork2 and tag it with this
new exception. This option seems the most robust as it would allow a
more detailed log (e.g. where exactly the code fell over in it's
execution path). This way does seem a little over the top for
simplistic scenarios which is why I wonder if (1) is an acceptable
solution to this problem?
One of the major limitations with exception handling in .NET and Java is that there's no standardized means by which code can distinguish between an exception of some type which is thrown from a method for reasons that method expects, versus an exception of that same type which is thrown by a nested method, for reasons the outer method did not expect. If the purpose of a method is to call some user-supplied delegate, the only ways I know of to reliably distinguish between exceptions which are thrown by the called delegate and those which occurred in the process of calling it are either to pass the method an identity token which it will include in any exceptions it throws directly, or else have the method as a matter of policy wrap exceptions that occur while invoking the user-supplied callback. Neither method is terribly elegant.
Because there is no standardized way to identify exceptions which indicate that an operation failed "cleanly" without side-effects, from those which indicate that a more serious problem exists, I would suggest that code shouldn't rely upon "serious" exceptions to prevent "contagious" data corruption. Instead, any time an exception might cause an object to be left in a corrupt state, the object should be explicitly invalidated, to prevent corrupt data from being read from it and copied elsewhere (possibly overwriting what would have been the only good copy). In situations where the corrupted object isn't needed and stack unwinding would cause it to be invalidated, there is no problem. In situations where the object that was invalidated turns out to be essential for system operation, the program should be forcibly shut down and invalidating the object will make that happen more reliably than would throwing a "serious" exception.
Unfortunately, neither C# nor VB.NET provides a very nice pattern for guarding objects in this fashion. VB.NET has somewhat better exception-handling abilities than C#, and the correct pattern (taking action in a finally block based upon what exception was thrown, but without catching the exception) can be implemented, albeit awkwardly, in that language. In C# the only way to find out what exception occurs within a try block is to catch and rethrow, an action which has some side-effects.
There is an excellent interview with Anders Hejlsberg titled The Trouble with Checked Exceptions. (Anders led the team that designed the C# programming language.)
You are falling into the exception aggregation trap. You should probably not be asking "what exceptions could possibly be thrown by lower level systems?" The answer, in many cases, would be a list containing hundreds of unique exceptions.
Instead, you should ask yourself "how can I provide useful information to the developer?" You should document the exceptions that your code is explicitly throwing or, in rare cases, relevant exceptions that are very likely to occur and that the caller may be specifically interested in. The developer who calls your code can determine the necessity of handling those errors or passing that information along to the callers of their code - or simply doing nothing with it. Exceptions are exceptional, after all, and at a certain level it doesn't really matter which database error was thrown - the steps taken in response are the same (e.g. stabilize the environment if possible, write to the error log and terminate execution).

Try catch inside or out? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What's better and why:
This
public void Main()
{
SomeMethod();
}
public void SomeMethod()
{
try
{
// code
}
catch(Exception)
{
}
}
or this:
public void Main()
{
try
{
SomeMethod();
}
catch(Exception)
{
}
}
The answer is: "catch the exception at the lowest level that knows how to handle it."
There is a idea that you should be catching exceptions closest to where they occur (i.e. as high up the call stack as possible/appropriate). A blanket exception handler isn't typically a good idea because its drastically reduces the control flow available to you. Coarse-grained exception handling is quite importantly, but not a reasonable solution to program stability. Unfortunately, many beginner developers think that it is, and take such approaches as this blanket try-catch statement.
Saying this, if you have utilized exception handling properly (in a fine-grained and task-specific manner) in the rest of your program, and handled the errors accordingly there (rather than just displaying a generic error box), then a general try-catch for all exceptions in the Main method is probably a useful thing to have. One point to note here is that if you're getting bugs caught in this Main try-catch, then you either have a bug or something is wrong with your localized exception handling.
The primary usage of this try-catch with Main would be purely to prevent your program from crashing in very unusual circumstances, and should do hardly any more than display a (vaguely) user-friendly "fatal error" message to the user or just be left blank, as well as possibly logging the error somewhere and/or submitting a bug report.
Credits: Noldorin
See Exceptions and Exception Handling (C# Programming Guide) for guidance on exception handling in C#. This interview with Anders Hejlsberg is also informative.
The relevant guideline here is:
Do not catch an exception unless you can handle it and leave the application in a known state.
Generally, an exception should not be caught unless it can be properly handled. This could be either Main or SomeMethod, depending on what is coded. For instance, Main might include a general catch statement to handle general exceptions (and, for instance, write an error message to the console); but SomeMethod might be able to recover from certain exceptions and catch those.
Generally, catch {} (exception swallowing) should be avoided; a caller that cannot handle an exception should simply allow it to propagate upward.
There is no rule about which one is better. You can use both methods. The deal is you need to have the code that is most likely to throw an exception inside try and this applies to all programming language.
Let say the next happens:
You want a valid message for each failure.
public void Main()
{
try
{
SomeMethod();
}
catch(Exception)
{
}
}
The above will be less informative, than catching each try inside SomeMethod(), so even so there is no difference, I will suggest to catch small actions that might fail, to provide useful data about the cause of the error.
In my opinion you catch the exception in SomeMethod before it goes above and might get lost due to no immediate code visibility on the eyes
One very important thing is please try to catch the specific exception first rather than anything
e.g.
if SomeMethod is doing some string to number conversion then try to catch FormatException first and put the Exception class for anything else
I think, customizing will be the best way to throw more understandable exceptions at the lowest level.
first define your custom exception class
public class SomeException : Exception {}
public void SomeMethod()
{
try
{
// code
}
catch(Exception e)
{
throw new SomeException ("an error in somemethod",e);
}
}
now, you will catch more clearly exception at anywhere.

Categories

Resources