Possibly fixing exception in Catch - c#

Is it possible that I would bind a method and fix the error in the catch response? (for example take this code below)
try
{
if (icheck == 0)
{
BindRegister();
}
else
{
Label1.Text = "Error Message";
}
}
catch
{
icheck = 0;
BindRegister();
}
Is the catch just responsible for writing down the error message? (I'm using this code in my ASP.net web app)

Related

C# Are errors in DataGridView.Datasource assignments handled internally

I have an application that assigns a list of values to a DataGridView.
This is done inside a Try catch block.
Occasionally there is an issue with the with the procedure that produces this list (also in a try catch block) and this causes an error when the assignment is done.
It appears the exception is never caught by the block doing the assignment and the application freezes.
Is the exception handled inside the assignment call so that it is not propagated out to the catch block?
The exception produced as a pop up states
"The following exception occurred in the DataGridView:
System.IndexOutOfrangeException: Index 1 does not have a value at
System.Windows.Forms.dataGridViewDataConnection.GetError(Int32 rowIndex)
To replace this default dialog please handle the DataError event"
The code is basically
public void SetupRunners(EventDetails _eventDetails)
{
try
{
RunnerAssociates.Clear();
RunnerAssociates = null;
RunnerAssociates = createRunnerAssociateList(selectedEventDetails);
runnerAssociatesDataGridView.DataSource = RunnerAssociates;
runnerAssociatesDataGridView.DataMember = string.Empty;
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
}
private List<Runner_Associate> createRunnerAssociateList(EventDetails _meetAndRace) //NZRB_Global.MeetAndRace _meetAndRace)
{
const string methodName = "createRunnerAssociateList";
List<Runner_Associate> lra = new List<Runner_Associate>();
try
{
if (null != _meetAndRace)
{
_meetAndRace.UpdateAllProfiles();
foreach (RunnerDetail rd in _meetAndRace.runners.runnerList)
{
Runner_Associate ra = new Runner_Associate();
ra.Number = rd.number;
ra.RunnerName = rd.name;
RunnerProfile profile = rd.GetRunnerProfile();
if ((rbJockeyDriver.Checked) || (rbCustom.Checked))
{
ra.AssociateName = rd.person;
}
else if (profile != null)
{
if (rbTrainers.Checked)
{
ra.AssociateName = profile.trainer;
}
else if (rbOwners.Checked)
{
ra.AssociateName = profile.owners;
}
}
lra.Add(ra);
}
}
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
return lra;
}

Try and catch block is not catching format exception

I am trying to catch format exception but the program stops on try block and never reaches to catch block, what is the problem with the code
please help me?
private void txtBags_TextChanged(object sender, EventArgs e)
{
if (txtBags.Text != "" && PackingBox.Text != "")
{
try
{
txtQty.Text = ((Convert.ToDecimal(txtBags.Text)) *
(Convert.ToDecimal(PackingBox.Text)) / 100).ToString();
}
catch (FormatException eX)
{
MessageBox.Show(eX.Message);
}
}
else
{
txtQty.Text = "";
}
}
I want to catch the exception and show the message to the user?
please tell me how can I do that?
Why handle the exception at all? Why not just avoid it altogether by using TryParse?:
if (!string.IsNullOrEmpy(txtBags.Text) && !string.IsNullOrEmpty(PackingBox.Text))
{
if (!Decimal.TryParse(txtBags.Text, out var bags))
{
// handle parse failure
return;
}
if (!Decimal.TryParse(PackingBox.Text, out var packingBox))
{
// handle parse failure
return;
}
txtQty.Text = (bags * packingBox / 100).ToString();
}
If you're not building with Roslyn/are using an older version of C#, you might need to define the variable beforehand:
decimal bags;
if (!Decimal.TryParse(txtBags.Text, out bags))
And then the same with PackingBox, of course.

Interrupting long running method pattern

I am currently using this somewhat tedious pattern to generate error message for user running some long operation:
string _problem;
void SomeLongRunningMethod()
{
try
{
_problem = "Method1 had problem";
Method1();
_problem = "Unexpected error during doing something in Method2";
if(Method2())
{
_problem = "Method3 fails";
Method3();
}
_problem = "Not possible to obtain data";
var somedata = Method4();
}
catch(Exception)
{
MessageBox.Show("Problem with some long running method: " + _problem);
}
}
Either of methods may throw and I want to tell the user at which step failure occurs. This is done by setting _problem before running any of them.
In some cases I can use different Exception types to catch, but that doesn't works always, e.g. both Method1 and Method2 can throw InvalidOperationException().
This repeated code looks like a pattern. Though I can't recognize it. Any ideas? How to improve readability?
You could use when in the catch to differentiate between the same exception types and to check which method threw this exception:
void SomeLongRunningMethod()
{
try
{
Method1();
if (Method2())
{
Method3();
}
var somedata = Method4();
}
catch (InvalidOperationException invEx) when (invEx.TargetSite?.Name == nameof(Method1))
{
// ...
}
catch (InvalidOperationException invEx) when (invEx.TargetSite?.Name == nameof(Method2))
{
// ...
}
catch (Exception ex)
{
// ...
}
}
You could get the method that caused the exception using error.TargetSite. The only thing you need to change is your catch line: catch (Exception error)
I'd make a sequence of the things you want to do and run through them:
var methodList = new[]{
new{action = (Action)Method1, identifier = "Method1"},
new{action = (Action)Method2, identifier = "Method2"},
new{action = (Action)Method3, identifier = "Method3"},
};
string problem = null;
foreach(var info in methodList)
{
try
{
info.action();
}
catch(InvalidOperationException)
{
problem = string.Format("{0} failed", info.identifier);
break;
}
}
if(problem != null)
{
//notify
}

How to pass a thrown exception from a C# class to a C# Form

I have a project in c# which is split into UI layer and Business layer.
Basically I have a form where you can select an account and input a number for deposit. Once you click the OK button, your DepositTransaction.cs will handle the transaction.
Here is the sample code for DepositForm:
private void buttonOK_Click(object sender, EventArgs e) {
try {
bool inputTest;
decimal amount;
inputTest = decimal.TryParse(textBoxAmount.Text, out amount);
if (inputTest == false) {
throw new InvalidTransactionAmtException();
} else {
BankAccount account = comboBoxAccount.SelectedItem as BankAccount;
deposit = new DepositTransaction(account, amount);
this.DialogResult = DialogResult.OK;
}
} catch (InvalidTransactionAmtException ex) {
errorProviderDeposit.SetError(textBoxAmount, ex.Message);
textBoxAmount.Select();
textBoxAmount.SelectAll();
} catch (InvalidTransactionAmtNegativeException ex) {
errorProviderDeposit.SetError(textBoxAmount, ex.Message);
textBoxAmount.Select();
textBoxAmount.SelectAll();
} catch (AccountInactiveException ex) {
errorProviderDeposit.SetError(textBoxAmount, ex.Message);
textBoxAmount.Select();
textBoxAmount.SelectAll();
}
}
And now the sample code for the DepositTransaction
public override void DoTransaction() {
try {
if (Amount <= 0) { //Amount is the amount passed by the form
throw new InvalidTransactionAmtNegativeException();
}
if (acc.Active == false) { //acc is the account passed by the form
throw new AccountInactiveException();
}
acc.Credit(Amount);
Summary = string.Format("{0} {1}", Date.ToString("yyyy-MM-dd"), this.TransactionType);
this.setStatus(TransactionStatus.Complete);
} catch (InvalidTransactionAmtNegativeException ex) {
throw;
} catch (AccountInactiveException ex) {
throw;
}
}
However, trying the above, does not pass the error to the Form. It just crashes the program saying that the exception was not handled.
I saw another question on stackoverflow that mentioned the way to pass the error is just to use throw: and that error will be passed to the class that called this class (in my case the form), and it will be handled in the form.
What am I doing wrong?
Thank you
It just means that an exception that is neither of type InvalidTransactionAmtNegativeException nor AccountInactiveException is being thrown. Add new catch block
catch (Exception ex) {
throw;
}
EDIT: You should have it come last. It will catch any other exceptions that might be thrown within your DoTransaction method
You are repeating code in all your catch blocks in the UI, just use a generic catch block:
private void buttonOK_Click(object sender, EventArgs e) {
try {
bool inputTest;
decimal amount;
inputTest = decimal.TryParse(textBoxAmount.Text, out amount);
if (inputTest == false) {
throw new InvalidTransactionAmtException();
} else {
BankAccount account = comboBoxAccount.SelectedItem as BankAccount;
deposit = new DepositTransaction(account, amount);
deposit.DoTransaction();
this.DialogResult = DialogResult.OK;
}
//catch any type of exception here
} catch (Exception ex) {
errorProviderDeposit.SetError(textBoxAmount, ex.Message);
textBoxAmount.Select();
textBoxAmount.SelectAll();
}
}
It Seems that your exception doesn't comes under the specific exception you have given in catch block. So catch generic exception at the end. It is a good practice.

Returning a bool and rethrowing an exception

Is it possible to return a bool and also rethrow an exception within the same method? Ive tried with the following code and it keeps saying that unreachable code is detected or that i cant exit the finally block.
public bool AccessToFile(string filePath)
{
FileStream source = null;
try
{
source = File.OpenRead(filePath);
source.Close();
return true;
}
catch (UnauthorizedAccessException e)
{
string unAuthorizedStatus = "User does not have sufficient access privileges to open the file: \n\r" + filePath;
unAuthorizedStatus += e.Message;
MessageBox.Show(unAuthorizedStatus, "Error Message:");
throw;
}
catch (Exception e)
{
string generalStatus = null;
if (filePath == null)
{
generalStatus = "General error: \n\r";
}
else
{
generalStatus = filePath + " failed. \n\r";
generalStatus += e.Message;
}
MessageBox.Show(generalStatus, "Error Message:");
throw;
}
finally
{
if (source != null)
{
source.Dispose();
}
}
}
Once you throw an exception, processing in your current method finishes and the exception works up the call stack. Either handle your exceptions locally and then return your boolean, or throw them and let them bubble up and handle them at the front end.

Categories