24-C#笔记-异常处理
# 1 语法
try
catch
finally(相当于catch(...))
using System;
...
        public void division(int num1, int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
            finally
            {
                Console.WriteLine("Result: {0}", result);
            }
        }
---
# 2 异常类型
常见的异常是继承自System.Exception
System.ApplicationException 和 System.SystemException 类是派生于 System.Exception 类的异常类。
System.ApplicationException 类支持由应用程序生成的异常。所以程序员定义的异常都应派生自该类。
System.SystemException 类是所有预定义的系统异常的基类。
| System.IO.IOException | 处理 I/O 错误。 | 
| System.IndexOutOfRangeException | 处理当方法指向超出范围的数组索引时生成的错误。 | 
| System.ArrayTypeMismatchException | 处理当数组类型不匹配时生成的错误。 | 
| System.NullReferenceException | 处理当依从一个空对象时生成的错误。 | 
| System.DivideByZeroException | 处理当除以零时生成的错误。 | 
| System.InvalidCastException | 处理在类型转换期间生成的错误。 | 
| System.OutOfMemoryException | 处理空闲内存不足生成的错误。 | 
| System.StackOverflowException | 处理栈溢出生成的错误。 | 
---
# 3 自定义异常
用户自定义的异常类是派生自 ApplicationException 类。
using System;
namespace UserDefinedException
{
   class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature();
         try
         {
            temp.showTemp();
         }
         catch(TempIsZeroException e)
         {
            Console.WriteLine("TempIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}
public class TempIsZeroException: ApplicationException // 自定义异常
{
   public TempIsZeroException(string message): base(message)
   {
   }
}
public class Temperature
{
   int temperature = 0;
   public void showTemp()
   {
      if(temperature == 0)
      {
         throw (new TempIsZeroException("Zero Temperature found"));
      }
      else
      {
         Console.WriteLine("Temperature: {0}", temperature);
      }
   }
}
---
# 4 抛出异常
Catch(Exception e)
{
   ...
   Throw e
}
---
参考:
http://www.runoob.com/csharp/csharp-exception-handling.html
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号