Try-Catch is a statement keyword.
You could refer to Structured Exception Handling for more information.
There are two kinds of exceptions: hardware exceptions and software exceptions. Hardware exceptions are initiated by the CPU. They can result from the execution of certain instruction sequences, such as division by zero or an attempt to access an invalid memory address. Software exceptions are initiated explicitly by applications or the operating system. For example, the system can detect when an invalid parameter value is specified.
An example of TryCatch is as follows:
xaml:
<StackPanel Orientation="Horizontal">
<TextBox Name="tb1" Width="100" Height="40" Background="LightGreen"/>
<TextBox Name="tb2" Width="100" Height="40" Background="LightSkyBlue"/>
<Button Name="btn" Click="btn_Click" Width="100" Height="40" Content="devide"/>
</StackPanel>
Button click event:
private void btn_Click(object sender, RoutedEventArgs e)
{
try
{
int num1 = Int32.Parse(tb1.Text);
int num2 = Int32.Parse(tb2.Text);
var num3 = (double)(num1 / num2);
}
catch (DivideByZeroException dbze)
{
MessageBox.Show(dbze.ToString());
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.