try-catch-catch结构(多个异常的捕获和处理)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int m = 30000;
int n = 30000;
try {
n = 1 / (n - m);
int[,] a=new int[m,n];
}
catch(OutOfMemoryException e1){
Console.WriteLine("内存溢出异常:{0}", e1.Message);
}
catch(DivideByZeroException e2){
Console.WriteLine("零除异常:{0}",e2.Message);
}
}
}
}
运行结果:作用范围小的catch块放在前面,作用范围大的catch块放在后面。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int m = 1;
int n = 1;
try{
n = 1 / (m - n);
}
catch (DivideByZeroException e1){//派生类所在的catch块(作用范围小)
Console.WriteLine("产生异常1:{0}",e1.Message);
}
catch (ArithmeticException e2){//基类所在catch块(作用范围大)
Console.WriteLine("产生异常2:{0}",e2.Message);
}
}
}
}
运行结果: