2010年1月26日 星期二

[c#] 如何處理例外錯誤狀況 應用介紹-[try-catch-finally]

如何處理例外錯誤狀況 應用介紹-[try-catch-finally]

1.) NG程式
//錯誤程式,程式直接當掉(原因被除數不得維0)

private void button1_Click(object sender, EventArgs e)
{
int a = 0;
int b =100/a;
Console.WriteLine("b is {0}", b);

Console.WriteLine("End of job ");
}

2.) 攔截NG程式

//try-catch-finally語法(程式不會當掉,但提報錯誤)
private void button2_Click(object sender, EventArgs e)
{
int a = 0;
try
{
int b = 100 / a;
Console.WriteLine("b is {0}", b);
}
//錯誤攔截訊息
catch (Exception err1)
{
Console.WriteLine("Divided by zero ");
Console.WriteLine("Divided by zero {0}",err1 );
MessageBox.Show(err1.ToString ());
}
//最後一定會執行
finally
{
Console.WriteLine("End of job");
}

3.) 自行判斷NG錯誤跳轉攔截錯誤訊息(throw 使用)

//自行判斷錯誤跳轉攔截錯誤訊息(程式不會當掉,但提報錯誤)
private void button3_Click(object sender, EventArgs e)
{
int a = 100, b = 0;
try
{
if (b == 0)
{
//跳轉呼叫丟出錯誤
throw new ArithmeticException("Div by zero");
}
else
{
int c = a / b;
Console.WriteLine("Resoult is " + c);
}
Console.WriteLine("After divide2");
}
//
catch (ArithmeticException error)
{
Console.WriteLine("Caught!{0}",error );
}


===========================================
自訂錯誤類別-待續

2010年1月19日 星期二

[c#] String字串處理Split 應用介紹-[Split]

String字串處理Split 應用介紹-[Split]

//split
private void button_Click(object sender, EventArgs e)
{

char[] del = new char[] { ',','/' }; //多符號分離
//char del = ','; //單符號分離

string line = "datalog_mo1_0,2010/1/19下午 01:47:52,691,1,40197574905.7755";

string[] split = line.Split(del);

foreach (string s in split)
{
listBox1.Items.Add(s); //送到目標 listbox檢視
}

}

2010年1月2日 星期六

[SIEMENS SCL FC ] 由函式FC回傳演算計算 應用介紹-[SCL-FC ][IEC 61131-3]


由函式FC回傳演算計算 應用介紹-[SCL-FC][IEC 61131-3]


FUNCTION SQUARE : INT //帶回傳值


(*********************************************************

This function returns as its function value the square of the

input value or if there is overflow, the maximum value that

can be represented as an integer.

***********************************************************)


//know_how_protect //程式保護


//變數宣告in類型
VAR_INPUT

value : INT;

END_VAR


//程式開始
BEGIN


IF value <= 181 THEN

SQUARE := value * value; //計算含式

ELSE

SQUARE := 32_767; // overflow, 設定最大值並回傳當成錯誤碼

END_IF;


END_FUNCTION