This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to catch exceptions
I have not really had to use try and catch exceptions. I am trying to use a try/catch to trap for potential errors. Now I am not to sure where to put the try and catch this is the code I have right now..
divide d;
private void button1_Click(object sender, EventArgs e)
{
d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
int total = d.CalculateDivision();
MessageBox.Show(total.ToString());
}
now would I put it under here with
try
{
}
catch
{
MessageBox.Show("error");
}
or would I add the try/ catch somewhere in the code.
see http://msdn.microsoft.com/en-us/library/ms173160.aspx
The try goes around the code where the exception is thrown and the value is handled. in your example:
divide d;
private void button1_Click(object sender, EventArgs e)
{
try
{
d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
int total = d.CalculateDivision();
MessageBox.Show(total.ToString());
}
catch(Exception)
{
MessageBox.Show("error");
}
}
as you can only show the total if there is no exception.
Nope, that is right ;).
Just use it like what you showed us there:
try
{
// Your Code.
}
catch (Exception ex)
{
MessageBox.Show(ex);
}
You pretty much have the answer, if an exception is thrown though you can do this to get some more information about what might have caused it:
try
{
//your code:
d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
int total = d.CalculateDivision();
MessageBox.Show(total.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error has occured! " + ex.Message);
}
Another tip for you seeing as you are learning about Exception handling is to take a look at the finally block, this will get executed whether or not there was an exception, it goes after the try and catch blocks:
finally
{
// this code will always execute, maybe do some cleanup here
}
You would do something like this:
private void button1_Click(object sender, EventArgs e)
{
try
{
d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
int total = d.CalculateDivision();
MessageBox.Show(total.ToString());
}
catch(Exception error)
{
MessageBox.Show(error.Message);
}
}
Related
i have a onClick method on a buttom. when this button is pressed, i get a displayalert message.
getTokenQ has a value. my question why its going inside catch block?
private async void Button_Clicked(object sender, EventArgs e)
{
try
{
var getTokenQ = await SecureStorage.GetAsync("Save_Security_Question");
if ((String.IsNullOrWhiteSpace(getTokenQ) == false))
{
}
else
{
}
}
catch (Exception ex)
{
await DisplayAlert("Message", "Some thing went wrong. Please try different method", "ok");
}
}
no you don't need to do that, you can use .Result if you don't want to execute your code asynchronously , this code is perfectly fine :
private void Button_Clicked(object sender, EventArgs e)
{
try
{
var getTokenQ = SecureStorage.GetAsync("Save_Security_Question").Result;
if ((String.IsNullOrWhiteSpace(getTokenQ) == false))
{
}
else
{
}
}
catch (Exception ex)
{
DisplayAlert("Message", "Some thing went wrong. Please try different method", "ok");
}
}
Why in catch ! Because it's a message to display only if an exception is thrown.
So I have a stack of calls. At the end of the stack an ArgumentException gets thrown. It propogates from to the last but one point where I have this code:
... Constructor(..){
try
{
this.Issuer = issuer;
this.Name = name;
this.Secret = secret;
this.totpObj = new Totp(secret, 30, 6, mode);
this.id = Guid.NewGuid().ToString();
this.mode = mode;
this.valid = true;
}
catch (System.ArgumentException e)
{
throw e; // Also tried not having this --> option B
}
catch (Exception e)
{
}
}
And this code gets called from here:
private void addButtnClick(object sender, RoutedEventArgs e)
{
try
{
...
TOTPObj totpo = new TOTPObj(af.Accname, af.Issuer, secret, stype); // <--- FAILS
...
}
catch(Exception ex) // <--- SHOULD CATCH THIS?!
{
Console.WriteLine(ex);
Environment.Exit(ERROR_FAILED_ADD_KEY);
}
}
Now if I leave the "throw" in the first section of code I get:
While I think it should be caught at the next level? (second fragment of code).
If I don't throw the exception up but just do stuff there, I never get past the "<--- FAILS" point of code block two, the thread just exits. Why is that?
Here are the two alternatives i tried for catching errors, they both seem to do the same thing.. but is one preferable over the other and why ?
Alt 1:
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
try
{
Task t = Task.Run(() =>
{
_someObj.SomeMethod();
});
await t; //wait here, without blocking...
}
catch (Exception ex)
{
string errMsg = ex.Message + Environment.NewLine;
errMsg += "some unhandled error occurred in SomeMethod";
Log(errMsg);
return; //<-- bypass below code on error...
}
//other code below... does not execute...
DoSomethingElse();
}
Alt 2:
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
bool errOccurred = false;
Task t = Task.Run(() =>
{
try
{
_someObj.SomeMethod();
}
catch (Exception ex)
{
string errMsg = ex.Message + Environment.NewLine;
errMsg += "some unhandled error occurred in SomeMethod";
Log(errMsg);
errOccurred = true;
}//end-Catch
});
await t; //wait here, without blocking...
if (errOccurred) return; //<-- bypass below code on error...
//other code below... does not execute...
DoSomethingElse();
}
Better option is to refactor part of the code into a separate method returning a bool indicating that whether to proceed or not.
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
bool success = await SomeMethodAsync();
if (!success)
{
return;
}
//other code below... does not execute...
DoSomethingElse();
}
private async Task<bool> SomeMethodAsync()
{
try
{
await Task.Run(() => _someObj.SomeMethod());
return true;
}
catch (Exception ex)
{
string errMsg = string.Format("{0} {1}some unhandled error occurred in SomeMethod",
ex.Message, Environment.NewLine);
Log(errMsg);
return false;
}
}
It's better to refactor the code than putting it all at the same place.It's better to catch the exception within your delegate if all you need to do is log it.
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
try
{
DoSomeWork();
}
catch (Exception ex)
{
log.Error(ex.Message);
}
});
}
However If you have another method DoSomethingElse() which might be affected by the outcome of the Task.It's better to wrap try catch around await
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
try
{
await Task.Run(() =>
{
try
{
DoSomeWork();
}
catch (Exception ex)
{
log.Error(ex.Message);
}
});
DoSomethingElse();
}
catch(Exception ex)
{
}
}
As with anything it depends.
I'd say refactor the Task.Run() section into a separate async Task method, much like Sriram Sakthivel's answer, is in general a good thing. It avoids the use of a captured bool in the lambda as in version 2, and it lets you write code that expresses intent more concisely.
That said, I would carefully consider if the "catch all -> log -> ignore" pattern is what you want. In general: catch specific exceptions and handle them specifically. For all other exceptions, you might log them, but still rethrow them with "throw;" or "throw new MoreSpecificException(originalException);".
With that in mind I would suggest that if you do the catch all approach you should do the catch all as in version 1.
To keep readability high, make the code concise with clear intent, and be explicit about handling exceptions, I would write it something like this:
private async void BtnClick(object sender, RoutedEventArgs e)
{
try
{
if (await TryDoSomethingAsync())
{
DoSomeMoreStuff();
}
}
catch (Exception ex)
{
// I am sure it is fine that any and all exceptions can be logged and ignored.
Log(ex);
// And maybe even notify the user, since I mean, who monitors log files anyway?
// If something that shouldn't go wrong goes wrong, it's nice to know about it.
BlowUpInYourFace(ex);
}
}
private async Task<bool> TryDoSomethingAsync()
{
return await Task.Run<bool>(() =>
{
try
{
_myService.DoSomething();
}
catch (SomeKnownException ske)
{
// An expected exception which is fine to ignore and return unsuccessful.
Log(ske);
return false;
}
catch (SomeOtherKnownException soke)
{
// Expected exception that indicates something less trivial, but could be more precise.
throw new MyMorePreciseException(soke);
}
// Nothing went wrong, so ok.
return true;
});
}
I want to throw an exception at next catch, (I attached image)
Anybody know how to do this?
C# 6.0 to the rescue!
try
{
}
catch (Exception ex) when (tried < 5)
{
}
You can't, and trying to do so suggests that you've got too much logic in your catch blocks, or that you should refactor your method to only do one thing. If you can't redesign it, you'll have to nest your try blocks:
try
{
try
{
...
}
catch (Advantage.Data.Provider.AdsException)
{
if (...)
{
throw; // Throws to the *containing* catch block
}
}
}
catch (Exception e)
{
...
}
On the other hand, as of C# 6, there are exception filters so you can check a condition before actually catching the exception:
try
{
...
}
catch (Advantage.Data.Provider.AdsException) when (tries < 5)
{
tries++;
// etc
}
// This will catch any exception which isn't an AdsException *or* if
// if the condition in the filter isn't met.
catch (Exception e)
{
...
}
One possibility is nesting the try/catch clause:
try
{
try
{
/* ... */
}
catch(Advantage.Data.Provider.AdsException ex)
{
/* specific handling */
throw;
}
}
catch(Exception ex)
{
/* common handling */
}
there is also another way - using only your general catch statement and checking the exception type yourself:
try
{
/* ... */
}
catch(Exception ex)
{
if(ex is Advantage.Data.Provider.AdsException)
{
/* specific handling */
}
/* common handling */
}
This answer is inspired by Honza Brestan's answer:
}
catch (Exception e)
{
bool isAdsExc = e is Advantage.Data.Provider.AdsException;
if (isAdsExc)
{
tried++;
System.Threading.Thread.Sleep(1000);
}
if (tried > 5 || !isAdsExc)
{
txn.Rollback();
log.Error(" ...
...
}
}
finally
{
It's ugly to have two try blocks nested inside each other.
If you need to use properties of the AdsException, use an as cast instead of is.
I have this C# windows application. Exceptions occur at times. When an exception occurs, I want to drill down on the Error Code for that exception and then fetch and print it.
Posting sample code
public void CreateSkill(int row)
{
try
{
Excel1.MWMClient.MWMServiceProxy.Skill skill = new Excel1.MWMClient.MWMServiceProxy.Skill();
skill.name = "perl";
// skill.description = "bowler";
skill.expertiseLevel = "3";
skill.ID = 1;
Console.WriteLine(skillClient.CreateSkill(skill));
Console.WriteLine(skill.ID);
ExcelRecorder(null, row);
}
catch (Exception ex)
{
ExcelRecorder(ex.Message, row);
}
finally
{
System.GC.Collect();
}
}
ExcelRecorder() is a method which prints the exception message in a cell in an excel sheet.
I want to print the exception as well as the error code in my excel sheet. How do I fetch this error code through my code?
Posting an image
Try this one:
try {
}
catch(Exception e) {
int code = e.HResult;
}
or even:
try {
}
catch (Exception e){
var Wex = e as Win32Exception;
int code = Wex.ErrorCode;
};