using
System;
using System.IO;
namespace ConsoleApp
{
class App
{
// 自定义异常类
public class MyException : ApplicationException
{
public MyException(string message) : base(message)
{
}
public MyException(string message,Exception
innerException)
: base(message,innerException)
{
}
}
// 实例化异常对象,并抛出异常
private static void ThrowException()
{
//throw new NotImplementedException();
throw new FileNotFoundException();
//throw new IOException();
}
public static void Main()
{
Console.Write(">>> Test01" + (char)10);
Test01();
Console.Write(">>> Test02"
+ (char)10);
Test02();
Console.Write(">>> Test03"
+ (char)10);
Test03();
}
private static void Test01()
{
try
{
try
{
throw new MyException("My error.");
}
catch(MyException ex)
{
Console.WriteLine("MyException: " + ex.Message);
}
catch
{
Console.WriteLine("Unexpected error!");
}
finally
{
Console.WriteLine(" --- inside finally ---");
}
ThrowException();
}
catch(IOException ex)
{
Console.WriteLine("IOException: " + ex.Message);
}
catch(ApplicationException ex)
{
Console.WriteLine("ApplicationException: " + ex.Message);
}
catch(SystemException ex)
{
Console.WriteLine("SystemException: " + ex.Message);
}
catch
{
Console.WriteLine("Unexpected error!");
}
finally
{
Console.WriteLine(" --- outside finally ---");
}
Console.ReadLine();
}
private static void Test02()
{
try
{
try
{
// 抛出自定义异常 MyException ,
// 但内层 catch 块中没有合适的处理程序存在
throw new MyException("My error.");
}
catch(IOException ex)
{
Console.WriteLine("IOException: " + ex.Message);
}
finally
{
Console.WriteLine(" --- inside finally ---");
}
}
catch(MyException ex)
{
Console.WriteLine("MyException: " + ex.Message);
}
catch(Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
finally
{
Console.WriteLine(" --- outside finally ---");
}
Console.ReadLine();
}
private static void Test03()
{
try
{
try
{
throw new IOException();
}
catch(IOException ex)
{
// 在 catch 块中抛出异常
throw new MyException("My error." + ex.Message);
}
catch(Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
finally
{
Console.WriteLine(" --- inside finally ---");
}
}
catch(Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
finally
{
Console.WriteLine(" --- outside finally ---");
}
Console.ReadLine();
}
}
}
|