/* Concepts: . What are exceptions? . Source of exceptions . Illegal user inputs (e.g. FormatException) . Programming errors (e.g. IndexOutOfBoundException) . System problems (e.g. OutOfMemoryException) . What can we do with an exception? . Catch it (try, catch): we want to handle . Do not rethrow: the exception should not disrupt the normal execution . Rethrow: the program should be disrupted, but we want to do something before that . Let the caller handle it: we don't want to handle/ we don't know how to handle . Finally: always execute (e.g. to release resources) . Can selectively handle some classes of exceptions . Actively throw exceptions (did not have time to cover) */ using System; public class ExceptionConcepts { public static void Main() { //IllegalUserInputs(); //ProgrammingErrors(); //SystemProblems(1000000); //CatchWithoutRethrow(); //CatchAndRethrow1(null); //CatchAndRethrow2(null); //ActiveThrow1(1, 0); //ActiveThrow2(1, 0); } static void IllegalUserInputs() { Console.Write("Please enter an integer: "); int i = int.Parse(Console.ReadLine()); } static void ProgrammingErrors() { int[] a = new int[5]; for (int i=0; i<=5; i++) a[i] = i; } static void SystemProblems(int i) { if (i > 0) SystemProblems(i-1); } static void CatchWithoutRethrow() { int i = 0; while (i <= 0) { try { Console.Write("Please enter a positive integer: "); i = int.Parse(Console.ReadLine()); if (i <= 0) Console.WriteLine("Sorry, the number is non-positive."); } catch (FormatException e) { Console.WriteLine("Sorry, it is not a valid integer."); } } } static int CatchAndRethrow1(string s) { try { int i = s.Length; return i; } catch(NullReferenceException e) { Console.WriteLine("null parameter is not allowed."); throw e; } } static int CatchAndRethrow2(string s) { try { int i = s.Length; return i; } catch(NullReferenceException e) { throw new NullReferenceException("null parameter is not allowed.", e); } } static int ActiveThrow1(int numerator, int denominator) { return numerator / denominator; } static int ActiveThrow2(int numerator, int denominator) { if (denominator == 0) throw new DivideByZeroException("Denominator parameter of ActiveThrow2 should not be zero."); else return numerator / denominator; } }