[C#基礎]-C# 的 try catch 介紹
[C#基礎]-C# 的 try catch 介紹
拷貝來源:
http://ithelp.ithome.com.tw/question/10074186
http://pydoing.blogspot.tw/2013/06/Csharp-try-catch-finally.html
try catch 語法如下,finally區塊可省略
try
{
//可能發生錯誤的地方
}
catch (Exception ex)
{
//例外要怎麼處理
}
finally
{
//不論是否產生例外都會執行的地方
}
class Demo {
static void Main() {
try {
object o2 = null;
int i2 = (int) o2;
System.Console.WriteLine(o2);
System.Console.WriteLine(i2);
}
catch {/*atch 沒有接任何參數 (parameter) ,表示任何例外 (exception) 都會處理*/
System.Console.WriteLine("something wrong");
}
System.Console.WriteLine("After try ....");
}
}
///////////////////////////////////////////////////
class Demo {
static void Main() {
try {
object o2 = null;
int i2 = (int) o2;
System.Console.WriteLine(o2);
System.Console.WriteLine(i2);
}
catch (System.NullReferenceException e) {
System.Console.WriteLine(e.ToString().Substring(0, 29));
}
catch {
System.Console.WriteLine("something wrong");
}
System.Console.WriteLine("After try ....");
}
}
/////////////////////////////////////////////
class Demo {
static void Main() {
try {
object o2 = null;
int i2 = (int) o2;
System.Console.WriteLine(o2);
System.Console.WriteLine(i2);
}
catch (System.NullReferenceException e) {
System.Console.WriteLine(e.ToString().Substring(0, 29));
}
catch {
System.Console.WriteLine("something wrong");
}
finally {
System.Console.WriteLine("finally");
}
System.Console.WriteLine("After try ....");
}
}
|