博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

异常类

Posted on 2010-10-18 21:29  EVON168  阅读(164)  评论(0编辑  收藏  举报
 
C#中,当出现某种异常时,就会创建一个异常对象。这个对象包含有助于跟踪问题的信息。我们可以创建自己的异常类,但.NET已经提供了许多预定义的异常类
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
int a = 255;
            
try
            {
                
checked
                {
                    
byte b = (byte)a;
                    Console.WriteLine(b);
                    Console.WriteLine(
10 / (a - a));
                }
            }
            
catch (System.OverflowException)
            {
                Console.WriteLine(
"a应该在0-255之间");
            }
            
catch (System.DivideByZeroException)
            {
                Console.WriteLine(
"除数不能为0");
            }
            
catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
            
finally
            {

            }

        }
    }
}

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo
{
    
class Program
    {
        
static void Demo(string a)
        {
            
try
            {
                
int ba = int.Parse(a);
                
if (ba < 0)
                {
                    
throw new Exception("小于0");//重新引发已捕获的异常
                }
            }
            
catch (Exception ex)
            {
                Console.WriteLine(
"在Demo中调用{0}", ex.Message);
                
throw ex;
            }
        }


        
static void Main(string[] args)
        {
            
try
            {
                Demo(
"-1");
            }
            
catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}