Csharp/CSharp Tutorial/Language Basics/Predefined Exception

Материал из .Net Framework эксперт
Версия от 12:19, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Check OverflowException for long

using System;
class MainClass
{
  static void Main(string[] args)
  {
    int MyInt = 12345000;
    long MyLong = MyInt;
    
    try
    {
      long c = checked(MyLong * 5000000);
    }
    catch (OverflowException e)
    {
      Console.WriteLine(e);
    }
  }
}

Define exception variable in catch statement: DivideByZeroException

using System;
class MainClass
{
   static void Main()
   {
      try
      {
         int y = 0;
         y = 10/y; 
      } catch (DivideByZeroException e) {
         Console.WriteLine("Message: {0}", e.Message);
         Console.WriteLine("Source: {0}", e.Source);
         Console.WriteLine("Stack: {0}", e.StackTrace);
      }
   }
}
Message: Attempted to divide by zero.
Source: main
Stack:    at MainClass.Main()

Generate an index out-of-bounds exception

using System; 
 
class MainClass { 
  public static void Main() { 
    int[] nums = new int[4]; 
 
    try { 
      Console.WriteLine("Before exception is generated."); 
 
      // Generate an index out-of-bounds exception. 
      for(int i=0; i < 10; i++) { 
        nums[i] = i; 
        Console.WriteLine("nums[{0}]: {1}", i, nums[i]); 
      } 
 
      Console.WriteLine("this won"t be displayed"); 
    } 
    catch (IndexOutOfRangeException) { 
      // catch the exception 
      Console.WriteLine("Index out-of-bounds!"); 
    } 
    Console.WriteLine("After catch statement."); 
  } 
}
Before exception is generated.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
Index out-of-bounds!
After catch statement.

Handle ArgumentOutOfRangeException

using System;
using System.Collections;
using System.Runtime.rupilerServices;
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = false)]
public class MainClass
{
    static void Main() {
        try {
            ArrayList list = new ArrayList();
            list.Add( 1 );
            Console.WriteLine( "Item 10 = {0}", list[10] );
        }
        catch( ArgumentOutOfRangeException x ) {
            Console.WriteLine( x );
            Console.WriteLine( "ArgumentOutOfRangeException Handler" );
        }
        catch( Exception x ) {
            Console.WriteLine( x );
            Console.WriteLine( "Exception Handler" );
        }
        catch {
            Console.WriteLine( "An exception I was not expecting..." );
            Console.WriteLine( "Unexpected Exception Handler" );
        }
        finally {
            Console.WriteLine( "Cleaning up..." );
        }
    }
}
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the s
ize of the collection.
Parameter name: index
   at System.Collections.ArrayList.get_Item(Int32 index)
   at MainClass.Main()
ArgumentOutOfRangeException Handler
Cleaning up...

Throwing Exceptions: ArgumentNullException

using System;
class MainClass
{
   static void Main()
   {
      string arg = null;
      
      try
      {
         if (arg == null)
         {
            ArgumentNullException MyEx = new ArgumentNullException();
            throw MyEx;
         }
      }
      catch (ArgumentNullException e)
      {
         Console.WriteLine("Message: {0}", e.Message);
      }
   }
}
Message: Value cannot be null.

Use the NullReferenceException.

using System;  
  
class MainClass {   
  public static void Main() {   
    try { 
      string str = null;
      Console.WriteLine(str.ToString());
      
    } catch (NullReferenceException) { 
      Console.WriteLine("NullReferenceException!"); 
      Console.WriteLine("fixing...\n"); 
 
    } 
 
  }  
}
NullReferenceException!
fixing...