Distinguish(区分)between bugs, errors, andexceptions.
1.bug是程序设计的失误,应该在编程之后由程序员找出
2.error是用户的错误行为,应该由程序员提前预测
3.而exceptions则是往往无法避免的,需要动用异常处理
try
{
Console.WriteLine("Entering try block...");
throw new System.ApplicationException();
Console.WriteLine("Exiting try block...");
}
catch
{
// Note: simplified example, it is not really solve the exception.
Console.WriteLine("Exception caught and handled.");
}
当抛出异常时,会跳过后面的语句直接去找catch
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter Main...");
Program t = new Program();
try
{
t.Func1();
}
catch
{
Console.WriteLine("catch it.");
}
Console.WriteLine("Exit Main...");
Console.ReadKey();
}
public void Func1()
{
Console.WriteLine("Enter Func1...");
Func2();
Console.WriteLine("Exit Func1...");
}
public void Func2()
{
Console.WriteLine("Enter Func2...");
throw new System.ApplicationException();
Console.WriteLine("Exit Func2...");
}
}
如果在函数中抛出的异常没有在函数中被捕捉到,会把这个函数从栈中弹出,程序跳到调用这个函数的位置
class Program
{
static void Main(string[] args)
{
try
{
double a = 5;
double b = 0;
Program t = new Program();
t.DoDivide(a, b);
}
catch (System.DivideByZeroException)
{
Console.WriteLine("DivideByZeroException");
}
catch (System.ArithmeticException)
{
Console.WriteLine("ArithmeticException");
}
catch (Exception e)
{
Console.WriteLine("e");
}
Console.ReadKey();
}
public double DoDivide(double a, double b)
{
if (b == 0) { throw new System.DivideByZeroException(); }
if (a == 0) { throw new System.ArithmeticException(); }
return a / b;
}
}
如果异常被前面的catch捕获,则后面的catch不能再捕获这个异常
finally
{
Console.WriteLine("finally");
//无论异常是否发生,这里的代码都会被执行
}