I'm making a calculator, that calculates the resistance from voltage and current given to the program. When the program calculates the value, it's supposed to log the datetime, the used voltage, the used current and the value of the resistance to a text file in the given filepath. My problem is with the try / catch, if the program is given a wrong filepath, the error doesn't occur and the program simply doesn't log anything, as it doesn't have the correct file path.
So I want to make the program to show the messagebox error message and show the ex.Message, then you should be able to give the correct filepath to the program, and continue.
I have tried to place the try / catch outside the if / else, and on the inside, but the program does the same thing, it doesn't show the error message.
Код: Выделить всё
namespace Resistance calculator
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
txtLogPath.Text = "C:\\Users\\MyUser\\Documents\\Log file.txt";
}
private void txtVoltage_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
txtVoltage.Clear();
}
private void txtCurrent_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
txtCurrent.Clear();
}
private void txtLogPath_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
txtLogPath.Clear();
}
private void btnCalculate_Click(object sender, RoutedEventArgs e)
{
if (double.TryParse(txtVoltage.Text, out double voltagevalue) &&
double.TryParse(txtCurrent.Text, out double currentvalue))
{
double Result = voltagevalue / currentvalue;
lblAnswer.Content = Result.ToString();
try
{
string logLine = DateTime.Now.ToString() + ", " + txtVoltage.Text + ", " + txtCurrent.Text + ", " + lblAnswer.Content;
System.IO.File.AppendAllText(txtLogPath.Text, logLine + "\n");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message + "Incorrect filepath!");
}
}
else
{
MessageBox.Show("Error occured, please write numbers only.");
}
}
}
}
Источник: https://stackoverflow.com/questions/781 ... showing-up