C#語法學習異常處理(Exception)
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();
}
}
}
申明
非源创博文中的内容均收集自网上,若有侵权之处,请及时联络,我会在第一时间内删除.再次说声抱歉!!!
博文欢迎转载,但请给出原文连接。