异常的相关操作参考博主令狐掌门的原文:
C#异常捕获try catch详细介绍_c# try-CSDN博客
异常处理类型:
System.Exception
是所有异常类的基类,它包含了异常的基本信息,如消息、堆栈跟踪等。
System.SystemException
它是系统定义的异常类的基类,通常由系统抛出。
ArgumentException
当向方法的参数传递了一个不合法或不适当的值时引发的异常。
ArgumentNullException
当向方法的参数传递了一个空引用(null)时引发的异常。
ArgumentOutOfRangeException
当向方法的参数传递了一个超出其有效范围的值时引发的异常。
ArithmeticException
在算术运算或类型转换期间发生错误时引发的异常。
IndexOutOfRangeException
当尝试访问数组或集合的无效索引时引发的异常。
InvalidCastException
当尝试执行无效的强制类型转换时引发的异常。
InvalidOperationException
当对象处于无法执行请求的操作的状态时引发的异常。
NullReferenceException
当应用程序尝试在需要对象的情况下使用空引用时引发的异常。
NotSupportedException
当调用某个对象不支持的操作或方法时引发的异常。
FormatException
当字符串的格式不正确时引发的异常。
例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace debugLearning
{
class Program
{
static void Main(string[] args)
{
int[] myArr = { 1, 2, 3, 4 };
try
{
int trmp = myArr[4];
}
catch(IndexOutOfRangeException e)
{
Console.WriteLine("下标越界");
}
catch(FieldAccessException e)
{
Console.WriteLine("发生FieldAccessException异常");
}
finally
{
Console.WriteLine("不管是否出现异常都会使用");
}
Console.WriteLine("23");
Console.ReadKey();
}
}
}
例子2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//检查用户输入数据是否合法
namespace trycatch1
{
class Program
{
static void Main(string[] args)
{
int n1;
int n2;
while (true)
{
try
{
n1 = Convert.ToInt32(Console.ReadLine());
n2 = Convert.ToInt32(Console.ReadLine());
break;
}
catch (FormatException)
{
Console.WriteLine("输入不符合规则,请从新输入");
}
}
Console.WriteLine(n1 + n2);
Console.ReadKey();
}
}
}