C#异常

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->■异常与错误
异常是可预见,可接受的,程序通过对异常的捕获和处理可以将异常带来的影响减小到最小;
错误是程序代码的错误,设计漏洞,是不可预见的,会给软件带来致命的影响
■捕获异常: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];
        }
    }
}

结果:

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:


你可能感兴趣的:(C++,c,C#,LINQ)