try-catch-finally结构:

为什么要用finally块?

程序在运行过程中一旦出现异常会立即转向执行相应catch块中的语句,执行完后接着执行try-catch结构后面的语句。这意味着在出现异常时程序并不是按照既定的顺序执行,而是跳转执行。
为维持系统的有效性和稳定性,必须保证有相应的代码能够“弥补”被跨越代码的工作,主要是完成必要的清理工作(如关闭文件、释放内存等)。这种保证机制可以由带finally的try-catch-finally结构来实现。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class userException:Exception{
public userException() { }
public userException(string ms) : base(ms) { }
public userException(string ms, Exception inner) : base(ms, inner) { }
}
class Student {
private string name;
private double score;
public void setInfo(string name,double score) {
if(name.Length>8){
throw (new userException("姓名的长度超过了8个字节!"));
}
if(score<0||score>100){
throw (new userException("非法的分数!"));
}
this.name = name;
this.score = score;
}
}
class Program
{
static void Main(string[] args)
{
//Student st = new Student();
//try {
// st.setInfo("adfadfaafafafafadga", 200);
//}
//catch(Exception e){
// Console.WriteLine("产生的异常:{0}",e.Message);
//}
//Console.ReadKey();
int m = 1;
int n = 1;
try
{
n = 1 / (m - n);
}
catch (Exception e1)
{//派生类所在的catch块(作用范围小)
Console.WriteLine("产生异常:{0}", e1.Message);
return;
Console.WriteLine("紧跟在return后面····");
}
finally{
Console.WriteLine("只要程序进入了try-catch-finally结构,都会执行finally块!");
}
Console.WriteLine("try-catch-finally结构后面的部分····");
Console.ReadKey();
}
}
}

运行结果:

Nearth===016/c#调试与异常的学习3(try-catch-finally)_派生类


滴滴答答一点一点学习,享受生活的味道~~~~~~~~~~~~~~~~~~~~~~~