Use try and catch statements to handle exceptions
[Csharp]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Windows;
Using System. Windows. Controls;
Using System. Windows. Data;
Using System. Windows. Documents;
Using System. Windows. Input;
Using System. Windows. Media;
Using System. Windows. Media. Imaging;
Using System. Windows. Navigation;
Using System. Windows. Shapes;
Namespace cam
{
/// <Summary>
/// Interaction logic of MainWindow. xaml
/// </Summary>
Public partial class MainWindow: Window
{
Public MainWindow ()
{
InitializeComponent ();
}
Private void button#click (object sender, RoutedEventArgs e)
{
Try
{
Int num1 = int. Parse (txtNum1.Text );
Int num2 = int. Parse (txtNum2.Text );
Int result = num1 + num2;
TxtResult. Text = result. ToString ();
}
Catch (FormatException cam) // format Error
{
MessageBox. Show (cam. Message );
}
Catch (OverflowException cam) // data Overflow
{
MessageBox. Show (cam. Message );
}
Catch (Exception cam)
{
MessageBox. Show (cam. Message );
}
}
}
}
Use checked and unchecked to check whether integer arithmetic operations have exceeded.
[Csharp]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace com
{
Class Program
{
Static void Main (string [] args)
{
Int number = int. MaxValue;
Console. WriteLine (number );
Try
{
Checked
{
Number ++;
}
}
Catch (Exception cam)
{
Console. WriteLine (cam. Message );
}
Console. WriteLine (number );
}
}
}
Try, catch, and finally are common syntax structures used to control program flows that may encounter exceptions. catch and finally must have at least one. If return exists in the try block, finally will still execute
[Csharp]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace com
{
Class Program
{
Static void Main (string [] args)
{
Int number = int. Parse (Console. ReadLine ());
Try
{
String name = dayName (number );
Console. WriteLine (name );
}
Catch (ArgumentOutOfRangeException ex)
{
Console. WriteLine (ex. Message );
}
Finally
{
Console. WriteLine ("program ended ");
}
}
Static string dayName (int number)
{
Switch (number)
{
Case 1:
Return "Monday ";
Case 2:
Return "Tuesday ";
Case 3:
Return "Wednesday ";
Case 4:
Return "Thursday ";
Case 5:
Return "Friday ";
Case 6:
Return "Saturday ";
Case 7:
Return "Sunday ";
Default:
Throw new ArgumentOutOfRangeException ("incorrect date input"); // manually throw an error
}
}
}
}