C#中的try catch finally用法分析
更新時間:2014年12月26日 10:02:19 投稿:shichen2014
這篇文章主要介紹了C#中的try catch finally用法,以實例形式分析了try catch finally針對錯誤處理時的不同用法,具有一定的參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#中的try catch finally用法。分享給大家供大家參考。具體分析如下:
try中的程序塊是有可能發(fā)生錯誤的程序塊,catch中的程序塊是當發(fā)生錯誤的時候才會執(zhí)行的代碼塊,finally中的程序塊是無論是否發(fā)生錯誤都會執(zhí)行的代碼塊。
示例程序:
復制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample_01_CA
{
public class Complex
{
static void Main(string[] args)
{
int i = 2008;
int j = 0;
try
{
int result = i / j;
}
catch
{
Console.WriteLine("J變量的值為0");
}
finally
{
Console.WriteLine(j.ToString());
}
Console.Read();
}
};
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample_01_CA
{
public class Complex
{
static void Main(string[] args)
{
int i = 2008;
int j = 0;
try
{
int result = i / j;
}
catch
{
Console.WriteLine("J變量的值為0");
}
finally
{
Console.WriteLine(j.ToString());
}
Console.Read();
}
};
}
程序輸出為:
J變量的值為0
0
示例程序:
復制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample_01_CA
{
public class Complex
{
static void Main(string[] args)
{
int i = 2008;
int j = 2;
try
{
int result = i / j;
}
catch
{
Console.WriteLine("J變量的值為0");
}
finally
{
Console.WriteLine(j.ToString());
}
Console.Read();
}
};
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample_01_CA
{
public class Complex
{
static void Main(string[] args)
{
int i = 2008;
int j = 2;
try
{
int result = i / j;
}
catch
{
Console.WriteLine("J變量的值為0");
}
finally
{
Console.WriteLine(j.ToString());
}
Console.Read();
}
};
}
程序輸出為:
0
希望本文所述對大家的C#程序設計有所幫助。
相關文章
C#中把FastReport.Net報表控件的數(shù)據(jù)保存到數(shù)據(jù)庫
這篇文章介紹了在數(shù)據(jù)庫中保存FastReport.Net報表的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06C#中static void Main(string[] args) 參數(shù)示例詳解
這篇文章主要介紹了C#中static void Main(string[] args) 參數(shù)詳解,本文通過具體示例給大家介紹的非常詳細,需要的朋友可以參考下2017-03-03