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.
Related
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)
I am trying to catch FormatException from a text box. For example - if user enters number or any other character inside name text box field. Message will pop up - something went wrong. I'm fairly new to C# and I don't understand the concept of exceptions. Below does not work. What is correct exception for invalid format?
private void button1_Click(object sender, EventArgs e)
{
try
{
string name = textBox1.Text;
int age = int.Parse(textBox2.Text);
}
catch (FormatException )
{
MessageBox.Show("Something went wrong");
}
Try this to show the message.
try
{
double mydoubleParam = 0;
// Assuming textBox1.Text is Name test box
if (double.TryParse(textBox1.Text, out mydoubleParam))
{
new Exception(" Numeric value in name field");
}
int age = int.Parse(textBox2.Text);// Assuming Number text box
MessageBox.Show("How are you today?");
}
catch (FormatException ex)
{
MessageBox.Show("Something went wrong");
}
you can handle it in the TextChanged event like this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool isNumeric = int.TryParse(textBox1.Text, out a);
if (isNumeric)
{
MessageBox.Show("Something went wrong");
}
}
catch (FormatException ex)
{
MessageBox.Show("Something went wrong " + ex.ToString() );
}
USE ex as variable in Catch.
UPDATE (As per comment )
catch (FormatException ex)
{
MessageBox.Show("Something went wrong !");
}
If you need to check for numbers inside the name textbox, then:
try {
string name = textBox1.Text;
Regex regex = new Regex("[0-9]");
if (regex.IsMatch(name)) {
throws new FormatException();
}
int age = int.Parse(textBox2.Text);
MessageBox.Show("How are you today?");
}
catch (FormatException) {
MessageBox.Show("Something went wrong");
}
You should also show a more specific message for each of the cases.
UPDATE
What you should really be doing is:
var regex = new Regex("[0-9]");
if (regex.IsMatch(textBox1.Text)) {
MessageBox.Show("There was a number inside name textbox.","Error in name field!");
return;
}
try {
Convert.ToInt32(textBox2.Text);
} catch (Exception) {
MessageBox.Show("The input in age field was not valid","Error in name field!");
return;
}
I'm getting unreachable code warning in catch block and I'm not able to debug. Please suggest me how to rectify that bug:
private void HandleDevelopmentServer()
{
string sErrMsg = "";
try
{
QuasarInterfaces.ISecurity oSecurity = null;
Global.CreateSecurityComponent(ref oSecurity);
System.Data.DataSet oDS;
DataTable dtDBSettings = new DataTable();
string sDBString = System.Configuration.ConfigurationSettings.AppSettings["Environment"];
Global.ReadDBConfig(sDBString, ref dtDBSettings);
oSecurity.FetchAllUsers(out oDS, out sErrMsg, dtDBSettings)
if (sErrMsg.Length > 0)
throw new Exception(sErrMsg);
if ((oDS != null) && (oDS.Tables.Count != 0))
{
DropDownList1.DataSource = oDS;
DropDownList1.DataBind();
}
}
catch (Exception e)
{
throw new Exception("HandleDevelopmentServer function failed;" + e.Message);
Global.writeLog("" + e.ToString());
}
}
This line will never happen:
Global.writeLog("" + e.ToString());
You are throwing an exception just above it, meaning this method will exit at that point to the previous in the call stack
By just switching the two it will be fine.
catch (Exception e)
{
Global.writeLog("" + e.ToString());
throw new Exception("HandleDevelopmentServer function failed;" + e.Message);
}
And you can also remove the "" +.
You have to switch the two lines in the catch block so that the log is written before the exception is thrown.
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.
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.