EXCEPTION
◎ 常用的 EXCEPTION 的 Field / Function
- System.Exception.Message:錯誤原因
- System.Exception.StackTrace:印出追蹤的錯誤訊息
- System.Exception.GetType().Name:錯誤的類型,e.g:FileNotFoundException、SqlException、FormatException、OverflowException、DivideByZeroException
◎ EXCEPTION 的子類別(Exception的類型)
- System.FileNotFoundException
- System.SqlException
- System.FormatException
- System.OverflowException
- System.DivideByZeroException
◎ 範例程式碼
using OnLineGame;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ExceptionDemo
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("================最簡單的 Exception 範例================");
//TryCatchSample1();
//Console.WriteLine("================巢狀 TryCatch================");
//NestedTryCatch();
//Console.WriteLine("================自定義屬於自己的 Exception================");
//NoVpnConnectionSample();
Console.ReadLine();
}
#region 最簡單的 Exception 範例
public static void TryCatchSample1()
{
StreamReader reader = null;
StreamWriter writer = null;
try
{
// Reader
reader = new StreamReader(@"D:\0_DeleteMe\Data.txt");
string readerInputStr = reader.ReadToEnd();
Console.WriteLine(readerInputStr);
// Writer.
string filePath = @"D:\0_DeleteMe\Data2.txt";
writer = new StreamWriter(filePath);
writer.Write(readerInputStr);
writer.Close();
Console.WriteLine("StreamWriter Updated.");
}
catch (FileNotFoundException ex)
{
//if the fielPath doesn't exist, throw System.FileNotFoundException
Console.WriteLine("{0} can not be found. Please create it.\n", ex.FileName);
Console.WriteLine("Exception Message : {0} \n", ex.Message);
Console.WriteLine("Stack Trace : {0} \n", ex.StackTrace);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
finally
{
//if (reader != null)
//{
// reader.Close();
//}
reader?.Close();
}
}
#endregion
#region 巢狀 TryCatch
public static void NestedTryCatch()
{
try
{
try
{
Console.WriteLine("請輸入被除數:");
int dividend = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("請輸入除數:");
int divisor = Convert.ToInt32(Console.ReadLine());
int quotient = dividend / divisor;
Console.WriteLine("計算結果 = {0}", quotient);
}
catch (Exception ex)
{
//「\n」代表換行 for Console
//ex.GetType().Name會回傳是什麼樣類型的錯誤,e.g:FormatException、OverflowException、DivideByZeroException
Console.WriteLine("Exception : {0} \nMessage : {1} \nStackTrace : {2} \n", ex.GetType().Name, ex.Message, ex.StackTrace);
#region 產生 log 檔案
string filePath = @"D:\0_DeleteMe\Log.txt";
if (File.Exists(filePath))
{
#region 若 Log 檔案存在,則繼續往下寫
StreamWriter writer = new StreamWriter(filePath);
//「\r\n」代表換行 for Console for file,「r」means return,n means new line.
writer.Write("Exception : {0} \r\nMessage : {1} \r\nStackTrace : {2} \r\n", ex.GetType().Name, ex.Message, ex.StackTrace);
writer.Close();
Console.WriteLine("Error Log 已更新!!!");
#endregion
}
else
{
//拋出一個 FileNotFoundException 類型的錯誤給 外面的 catch 接
throw new FileNotFoundException(filePath + " does not Exist, please create it. \n", ex);
}
#endregion
}
}
catch (Exception ex)
{
//outer Try Catch Clause
//ex.Message return the current exception message from outer Try Catch Clause.
Console.WriteLine("Current Exception Message from outer Try Catch Clause : {0} \n", ex.Message);
//if the writer filePath doesn't exist, here will catch System.FileNotFoundException
//inner Try Catch Clause
//ex.InnerException.Message return the exception message from inner Try Catch Clause.
//if ex.InnerException is exist then print it.
if (ex.InnerException != null)
{
Console.WriteLine("Exception Message From Inner Try Catch Clause : {0} \n", ex.InnerException.Message);
}
// E.g.1.
// Enter "A" will cause System.FormatException
// E.g.2.
// Enter "12345678901" will cause System.OverflowException
// E.g.3.
// Enter "0" in Divisor will cause System.DivideByZeroException
}
}
#endregion
#region 自定義屬於自己的 Exception
public static void NoVpnConnectionSample()
{
try
{
throw new NoVpnConnectionException("User is using vpn");
}
catch (NoVpnConnectionException ex)
{
Console.WriteLine(ex.Message);
}
}
#endregion
}
}
#region 自定義自己的 Exception
// 3. -------------------------------------------------------------
// Custom Exceptions
//Sometimes there is no existing system exception can fit your situation.
//In this case, you might have to create your own Customize Exceptions.
namespace OnLineGame
{
//The Customize Exceptions must extend the System.Exception class.
//In addition the suffix should be "Exception" to fulfill the naming convention.
[Serializable]
public class NoVpnConnectionException : Exception
{
// The Customize Exceptions should always provide a public constructor
//which take a string message parameter,
//and then pass it to base class constructor.
public NoVpnConnectionException(string message)
: base(message)
{
}
//The Customize Exceptions should always provide the capability to handle inner exception.
public NoVpnConnectionException(string message, Exception innerException)
: base(message, innerException)
{
}
//The Customize Exceptions should always support Serializable, thus,
//it can work across application domains.
public NoVpnConnectionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
#endregion