Try catch not showing error message for formatException - c#

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;
}

Related

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll, network releted

private void metroButtonLogin_Click(object sender, EventArgs e)
{
try
{
//Your insert code here
DataSet1TableAdapters.UsersTableAdapter userAda = new DataSet1TableAdapters.UsersTableAdapter();
DataTable dt = userAda.GetDataByUserAndPass(metroTextBoxUser.Text, metroTextBoxPass.Text);
if (dt.Rows.Count > 0)
{
//valid
MessageBox.Show("Login Ok");
UserID = int.Parse(dt.Rows[0]["UserID"].ToString());
loginFlag = true;
}
else
{
// not valid
MessageBox.Show("Access Denied");
loginFlag = false;
}
Close();
}// above is your origine code
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
}
}
You need to look at more details of your exception to better understand what's wrong. You need to look at the Message property of the exception. Usually it will give a more understandable sentence about what the problem could be. Add that last line of code in your metroButtonLogin_Click method in a try/catch block and have a look at the exception.

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.

Exception thrown by page redirection in asp.net

I have this code
protected void Button_Click(object sender, EventArgs e)
{
try
{
// some code
con.Open();
string result = command.ExecuteScalar().ToString();
if (result != string.Empty)
{
// some code
Response.Redirect("Default.aspx");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
It gives an exception from Response.Redirect("Default.aspx");
ex: Thread was being aborted.
any idea why?
thanx
Redirecting from within a Try...Catch statement will result in this Exception being thrown, so this is not what you want to do.
I would update your code to;
string result = string.Empty;
try
{
// some code
con.Open();
result = command.ExecuteScalar().ToString();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
if (result != string.Empty)
{
// some code
Response.Redirect("Default.aspx");
}
This is a typical Exception that is thrown by ASP.NET when performing a redirect. It's quite well documented on the Interweb.
Try the following catch block to swallow the exception and all should be fine. It's supposed to do nothing!
catch(ThreadAbortException)
{
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}

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.

how to throw an exception from a class back to the form that called it

Hello I have a regular WinForm that calls this:
private void childDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
SQL.createTable("childDirectory"); //THIS LINE
}
catch(SystemException ecp)
{
MessageBox.Show(string.Format("An error occurred: {0}", ecp.Message));
}
}
and have a class named "SQL". The C# class cannot throw a messageBox to the user, only Console.WriteLine:
static public void createTable(string tableToCreate)
{
try
{
.
.
.
.
}
catch (SqlException exp)
{
Console.WriteLine("Database not created: " + exp.Message, "Error");
}
}
How can I throw this SqlExecption back in the Form.cs call? Sorry if my wording is wrong, hopefully you can understand what I'm trying to do.
static public void createTable(string tableToCreate)
{
try
{
.
.
.
.
}
catch (SqlException exp)
{
Console.WriteLine("Database not created: " + exp.Message, "Error");
throw exp;
}
}
And catch it with:
private void childDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
SQL.createTable("childDirectory"); //THIS LINE
}
catch(SystemException ecp)
{
MessageBox.Show(string.Format("An error occurred: {0}", ecp.Message));
}
catch (SqlException exp)
{
}
}
But unless it is necessary you don't need to catch exception in called method if you catch it in calling method.
Since you want to bubble up the exception I would suggest you simply don't catch it in the createTable method - instead add an exception handler for SqlException iny your childDirectoryToolStripMenuItem_Click method.
private void childDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
SQL.createTable("childDirectory"); //THIS LINE
}
catch (SqlException ex)
{
MessageBox.Show("Database not created: " + ex.Message);
}
catch(SystemException ecp)
{
MessageBox.Show(string.Format("An error occurred: {0}", ecp.Message));
}
}
Why not just let the error propogate up to the windows form, and avoid a double catch? You could do the logging there.
However, if you do indeed want to do it this way, then you would just call throw. This will simply rethrow the exception. The plus to this method over throw exp is that it will keep the original stack trace, and not mislead any debugging. An already vetted explanation for this can be found at: What is the proper way to re-throw an exception in C#?

Categories