異常類Exception

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->■Exception類的主要成員:
Exception:構造函數,構造一個異常類,制定其異常消息,發生位置
Message:只讀屬性,獲取當前異常提供的消息,該消息在構造異常時指定
Source:讀寫屬性,獲取和設置引起該異常的應用程序或對象的名稱
TargetSite:只讀屬性,獲取引發該異常的方法
ToString:公開方法,創建該異常的字符串表示形式,包括異常發生的位置,名稱等信息

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThrowException
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
try {
                ThrowAnException();
            }
catch(Exception e){
                ShowException(e);
            }
            System.Console.ReadLine();
        }
        
static void ThrowAnException() {
            
throw new Exception("This is an Exception!");
        }
        
static void ShowException(Exception e) {
            System.Console.WriteLine(
"An Exception information:");
            System.Console.WriteLine(
"Type:{0}  ",e.GetType().Name);
            System.Console.WriteLine(
"Message:{0}",e.Message);
            System.Console.WriteLine(
"Source:{0}",e.Source);
            System.Console.WriteLine(
"TargetSite:{0}",e.TargetSite);
            System.Console.WriteLine(
"ToString:{0}",e.ToString());
            System.Console.WriteLine(
"StackTrace:{0}",e.StackTrace);
        }
    }
}


結果:
An Exception information:
......Type:Exception
......Message:This is an Exception!
......Source:ThrowException
......TargetSite:Void ThrowAnException()
......ToString:System.Exception: This is an Exception!
   在 ThrowException.Program.ThrowAnException() 位置 g:"TrueStudy"cSharp"project
s"ConsoleAppl"ThrowException"Program.cs:行號 20
   在 ThrowException.Program.Main(String[] args) 位置 g:"TrueStudy"cSharp"projec
ts"ConsoleAppl"ThrowException"Program.cs:行號 13
......StackTrace:   在 ThrowException.Program.ThrowAnException() 位置 g:"TrueStu
dy"cSharp"projects"ConsoleAppl"ThrowException"Program.cs:行號 20
   在 ThrowException.Program.Main(String[] args) 位置 g:"TrueStudy"cSharp"projec
ts"ConsoleAppl"ThrowException"Program.cs:行號 13



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章