程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C#語法學習:異常處理(Exception)

C#語法學習:異常處理(Exception)

編輯:關於C#

using System;
class Test
{
static void Main()
{
/*
try
{
int n=10;
int m=0;
float f=n/m;
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("finally");
}
Console.WriteLine("finally later");
//*/

/*
try
{
int n=10;
int m=0;
float f=n/m;
}
catch(Exception e)
{
Console.WriteLine("ERROR");
}
finally
{
Console.WriteLine("finally");
}
Console.WriteLine("finally later");
//*/

/*
try
{
int n=10;
int m=0;
float f=n/m;
}
//這裡應該把庇配度高的異常放到前面,依次是庇配度越低的
//自然Exception也就放在最後面.
catch(DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("finally");
}
Console.WriteLine("finally later");
//*/

/*
try
{
int n=10;
int m=0;
float f=n/m;
}
//此處catch後面沒有跟(Exception e)
//程序會認為是catch(Exception e)
catch
{
Console.WriteLine("ERROR");
}
finally
{
Console.WriteLine("finally");
}
Console.WriteLine("finally later");
//*/

/*
try
{
string s = null;
if(s==null)
{
throw new ArgumentNullException();
}
}
catch
{
//這裡拋出一個異常
Console.WriteLine("接收到拋出的異常");
}
finally
{
Console.WriteLine("finally");
}
Console.WriteLine("finally later");
//*/

}
}

/*
* Created by SharpDevelop.
* User: Administrator
* Date: 2008/9/11
* Time: 下午 04:16
*
*/
using System;
using System.IO;
public class Exceptions
{
public static int Main()
{
byte[] myStream=new byte[3];
StreamWriter sw=new StreamWriter("exceptions.txt");
try
{
for(byte b=0;b<10;b++)
{
sw.WriteLine("Byte {0}:{1}",b+1,b);
myStream[b]=b;
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
sw.WriteLine("Close");
sw.Close();
}
return 0;
}
}

/*
* Created by SharpDevelop.
* User: Administrator
* Date: 2008/9/11
* Time: 下午 04:29
*
*/
using System;
using System.IO;
public class TooManyItemsException:Exception
{
public TooManyItemsException():base(@"自己設計的異常信息"){}
}
public class ExceptionTester
{
public static int Main()
{
ExceptionTester myExceptionMaker=new ExceptionTester();
try
{
myExceptionMaker.GenerateException(5);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Finally from Main.");
}
return 0;
}
void GenerateException(int iterations)
{
int mySize=3;
byte[] myStream=new byte[mySize];
StreamWriter sw=new StreamWriter("aa.txt");
try
{
if(iterations>myStream.Length)
{
throw new TooManyItemsException();
}
for(byte b=0;b<iterations;b++)
{
sw.WriteLine("Byte {0}:{1}",b+1,b);
myStream[b]=b;
}
}
finally
{
Console.WriteLine("Finally from GenerateException.");
sw.WriteLine("Close");
sw.Close();
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved