■異常與錯誤
異常是可預(yù)見,可接受的,程序通過對異常的捕獲和處理可以將異常帶來的影響減小到最小;
錯誤是程序代碼的錯誤,設(shè)計漏洞,是不可預(yù)見的,會給軟件帶來致命的影響
■捕獲異常:try...catch
■拋出異常 throw語句
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace useException
{
class Program
{
static void Main(string[] args)
{
int val;
for (int i = -3; i < 12; i++) {
try {
val=GetValue(i);
System.Console.WriteLine("val:{0}",val);
}catch(Exception e){
System.Console.WriteLine("exception:{0}: ",e.Message);
}
}
System.Console.ReadLine();
}
static int GetValue(int index)
{
int[] ary = {0,1,2,3,4,5,6,7,8 };
if (index < 0) {
System.Console.Write("index={0} ",index);
throw new Exception("index<0");
}
if (index > 8){
System.Console.Write("index={0} ", index);
throw new Exception("index>8");
}
return ary[index];
}
}
}
結(jié)果:
index=-3 exception:index<0:
index=-2 exception:index<0:
index=-1 exception:index<0:
val:0
val:1
val:2
val:3
val:4
val:5
val:6
val:7
val:8
index=9 exception:index>8:
index=10 exception:index>8:
index=11 exception:index>8:
異常是可預(yù)見,可接受的,程序通過對異常的捕獲和處理可以將異常帶來的影響減小到最小;
錯誤是程序代碼的錯誤,設(shè)計漏洞,是不可預(yù)見的,會給軟件帶來致命的影響
■捕獲異常:try...catch
■拋出異常 throw語句
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace useException
{
class Program
{
static void Main(string[] args)
{
int val;
for (int i = -3; i < 12; i++) {
try {
val=GetValue(i);
System.Console.WriteLine("val:{0}",val);
}catch(Exception e){
System.Console.WriteLine("exception:{0}: ",e.Message);
}
}
System.Console.ReadLine();
}
static int GetValue(int index)
{
int[] ary = {0,1,2,3,4,5,6,7,8 };
if (index < 0) {
System.Console.Write("index={0} ",index);
throw new Exception("index<0");
}
if (index > 8){
System.Console.Write("index={0} ", index);
throw new Exception("index>8");
}
return ary[index];
}
}
}
結(jié)果:
index=-3 exception:index<0:
index=-2 exception:index<0:
index=-1 exception:index<0:
val:0
val:1
val:2
val:3
val:4
val:5
val:6
val:7
val:8
index=9 exception:index>8:
index=10 exception:index>8:
index=11 exception:index>8: