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.
Related
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
I'm trying to improve my MVC.NET Core-fu and I ended up in a bunch of methods in all my controllers looking like this (note the outermost, general, repetitive try-catch).
[HttpPost]
public IActionResult DoSomething([FromBody] Thing thing)
{
try
{
if (...)
return Ok(thing);
else
return NotFound();
}
catch (Exception) { return BadRequest(); }
}
The way I see, I want to have the baddy-requesty just in case. Now, that adds a lot of code to otherwise rather simple controller and I have a suspicion that someone before has thought of this and proposed a solution.
I haven't found such thing (and I was informed that filters are obsolete for usage in Core). Possibly it's because I'm not familiar with the right search keys.
This seems excessive to me. Many methods won't execute instructions that are likely to fail. For those extremely rare cases, a global error handler would be more than sufficient.
For those methods that access the disk, a database, or perform calculations that could raise exceptions (something you should probably be avoiding in the first place), a try...catch block makes sense.
But even in these cases, if a method with a try...catch handler calls another method, there is no reason to put handlers in that other method.
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.
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 7 years ago.
Improve this question
my code
public async Task<IHttpActionResult> Post(long? Workrequestid, string fileexist){ throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound,"this item does not exist"));}
error i am getting like
{ "message": "Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details."
}
according to me i need the message like "this item already exist". please help me
Your implementation does work as expected. Are you calling the API correctly? I've used TestController and posting to the following Uri and it works:
http://localhost:8075/api/test?workrequestId=1&fileexist=test
However, are you sure you want to explicitly throw an exception? When returning an IHttpActionResult it would be cleaner to simply return a 404 in the following way:
return this.NotFound();
Returning a NotFound error is telling the calling client all it needs to know, returning "this item does not exist" is redundant.
As there is no implementation on your code sample it's difficult to see your intention for the API other that it's a post. Depending on the circumstances, if appropriate, you could also return:
return this.BadRequest("this item does not exist.");
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.
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.