Csharp/C Sharp/Language Basics/throw
Exception Translation: CLR catches an exception and rethrows a different exception. The inner exception contains the original exception.
<source lang="csharp"> 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); } }
}
</source>
Throw and catch Exception
<source lang="csharp"> 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 } }
}
</source>
Throw exception from getter
<source lang="csharp"> 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 } }
}
</source>