Csharp/C Sharp/Language Basics/throw — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 11:39, 26 мая 2010

Exception Translation: CLR catches an exception and rethrows a different exception. The inner exception contains the original exception.

 
using System;
using System.Reflection;

public class MyClass {
    public static void MethodA() {
        Console.WriteLine("MyClass.MethodA");
        throw new Exception("MethodA exception");
    }
}
public class Starter {
    public static void Main() {
        try {
            Type zType = typeof(MyClass);
            MethodInfo method = zType.GetMethod("MethodA");
            method.Invoke(null, null);
        } catch (Exception except) {
            Console.WriteLine(except.Message);
            Console.WriteLine("original: " + except.InnerException.Message);
        }
    }
}


Throw and catch Exception

 
using System;
class ExceptionThrower {
    static void MethodOne() {
        try {
            MethodTwo();
        } finally { }
    }
    static void MethodTwo() {
        throw new Exception("Exception Thrown in Method Two");
    }
    public static void Main(String[] args) {
        try {
            ExceptionThrower FooBar = new ExceptionThrower();
            MethodOne();
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        } finally {
            // Cleanup code
        }
    }
}


Throw exception from getter

 
using System;
public class MyValue {
    public String Name;
}
class CardDeck {
    private MyValue[] Cards = new MyValue[52];
    public MyValue GetCard(int idx) {
        if ((idx >= 0) && (idx <= 51))
            return Cards[idx];
        else
            throw new IndexOutOfRangeException("Invalid Card");
    }
    public static void Main(String[] args) {
        try {
            CardDeck PokerDeck = new CardDeck();
            MyValue HiddenAce = PokerDeck.GetCard(53);
        } catch (IndexOutOfRangeException e) {
            Console.WriteLine(e.Message);
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        } finally {
            // Cleanup code
        }
    }
}