Throw exception from getter : throw « Language Basics « C# / C Sharp






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
        }
    }
}

 








Related examples in the same category

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