CSharp examples for Custom Type:Exception
To create your own exception, you must first declare it. Use the following format:
class ExceptionName : Exception {}
Creating and Throwing Your Own Exception
using System;//from www . ja va 2s .co m class MyThreeException : Exception {} class MathApp { public static void Main() { int result; try { result = MyMath.Util( 1, 2 ); Console.WriteLine( "Result of Util(1, 2) is {0}", result); result = MyMath.Util( 3, 4 ); Console.WriteLine( "Result of Util(3, 4) is {0}", result); } catch (MyThreeException) { Console.WriteLine("Ack! We don't like adding threes."); } catch (Exception e) { Console.WriteLine("Exception caught: {0}", e); } Console.WriteLine("\nAt end of program"); } } class MyMath { static public int Util(int x, int y) { if(x == 3 || y == 3) throw( new MyThreeException() ); return( x + y ); } }