0% found this document useful (0 votes)
27 views

Try Catch: Private Void Object Double Try

The document discusses using try/catch blocks to handle exceptions when converting user input strings to numeric values in C#. It shows three button click event handlers that try to convert textbox values to doubles, calculate operations on them, and display results, catching and handling any exceptions. It also shows using try/catch within a try/catch to handle specific exceptions at different levels and set error messages. Finally, it demonstrates checking user input as they type using try/catch and setting error messages if conversion fails.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Try Catch: Private Void Object Double Try

The document discusses using try/catch blocks to handle exceptions when converting user input strings to numeric values in C#. It shows three button click event handlers that try to convert textbox values to doubles, calculate operations on them, and display results, catching and handling any exceptions. It also shows using try/catch within a try/catch to handle specific exceptions at different levels and set error messages. Finally, it demonstrates checking user input as they type using try/catch and setting error messages if conversion fails.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Try catch

private void btnCalcular_Click(object sender, EventArgs e)


{
double valor=0;
try
{
valor = Convert.ToDouble(txtNum.Text);
valor = Math.Pow(valor, 2);
txtRes.Text = valor.ToString();
}
catch(Exception ex)
{
lblInfo.Text = ex.Message.ToString();
lblInfo.Text = "";
}
//valor = Math.Pow(valor, 2);
//txtRes.Text = valor.ToString();
}
private void btnSoma1_Click(object sender, EventArgs e)
{
double valor1, valor2;
try
{
valor1 = Convert.ToDouble(txtNum1.Text);
valor2 = Convert.ToDouble(txtNum2.Text);
txtRes.Text = (valor1 + valor2).ToString();
}
catch
{
lblInfo.Text = "Deve introduzir valores válidos";
}
}

private void btnSoma2_Click(object sender, EventArgs e)


{
double valor1, valor2;
try
{
valor1 = Convert.ToDouble(txtNum1.Text);
try
{
valor2 = Convert.ToDouble(txtNum2.Text);
txtRes.Text = (valor1 + valor2).ToString();

1
}
catch (Exception ex1)
{
lblInfo.Text = "2. valor deve ser válido";
}
}
catch (Exception ex2)
{
lblInfo.Text = "1 introduzir valores válidos";
}
}

private void txtNum2_TextChanged(object sender, EventArgs e)


{
try
{
Convert.ToDouble(txtNum2.Text);
errorProvider1.Clear();
btnSoma2.Enabled = true;
}
catch
{
errorProvider1.SetError(txtNum2, "Valor inválido");
btnSoma2.Enabled = false;
}
}

You might also like