异常处理 – 第六章 – C# 从入门到放弃

基本语法:

try
{
    ...
}
catch(Exception ex) when (ex.GetTypr() != typeof(System.OutOfMenoryException))
{
    ....
}

=====

数据溢出异常的处理:

checked:

int number = int.MaxValue;
checked
{
    int willThrow = number++;
    Console.WriteLine("won't run to here");
}

unchecked:

int number = int.MaxValue;
unchecked
{
    int willThrow = number++;
    Console.WriteLine("will run to here");
}

also:

try
{
    int lhs = 9876543;
    int rhs = 9876543;
    int outcome = 0;
    outcome = checked(lhs * rhs);
}
catch(OverflowException oEx)
{
    result.Text = oex.Message;
}

=====

手动抛出异常:

try
{
    throw new ArgumentOutOfRangeException("error!");
}
catch(ArgumentOutOfRangeException msg)
{
    xxx.Text = msg.Message;
}

finally的用法:

try
{
    DataConnection.Open();
    DataCommand.ExecuteReader();
    ...
    return;
}
finally
{
    DataConnection.Close();
}
//无论是否抛出异常,也无论从什么地方 return 返回,finally 语句块总是会执行,这样你有机会调用 Close 来关闭数据库连接(即使未打开或打开失败,关闭操作永远是可以执行的),以便于释放已经产生的连接,释放资源。 顺便说明,return 是可以放在 try 语句块中的。但不管在什么时机返回,在返回前,finally 将会执行。
//小结
try
{
    // 执行的代码,其中可能有异常。一旦发现异常,则立即跳到 catch 执行。否则不会执行 catch 里面的内容
}
catch
{
    // 除非 try 里面执行代码发生了异常,否则这里的代码不会执行
}
finally
{
    // 不管什么情况都会执行,包括 try catch 里面用了 return , 可以理解为只要执行了 try 或者 catch,就一定会执行 finally
}

发表评论

您的电子邮箱地址不会被公开。