most general way – not concrete – just something happened
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Program { static void Main(string[] args) { try { SomeClass sc = new SomeClass(); sc.SomeMethod(); } catch { Console.WriteLine("Some Exception happened..."); } } } |
simple example – catching Exception e
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace generalException2 { class Program { static void Main(string[] args) { SomeClass sc = new SomeClass(); try { sc.test(); } catch (Exception e) { Console.WriteLine("Method:{0}", e.TargetSite); // method Console.WriteLine("message:{0}", e.Message); // message Console.WriteLine("source:{0}", e.Source); // source Console.ReadLine(); } } } class SomeClass { public void test() { //some code throw new Exception("some message"); //some code } } } |
123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace generalException { class Program { static void Main(string[] args) { Car c = new Car("someName",20); try { for (int i = 0; i < 10; i++) { c.Accelerate(10); } } catch (Exception e) { Console.WriteLine("Method:{0}", e.TargetSite); // method Console.WriteLine("message:{0}", e.Message); // message Console.WriteLine("source:{0}", e.Source); // source Console.ReadLine(); } } } public class Car { public const int MaxSpeed = 100; public int CurrentSpeed { get; set; } private bool CarIsDead; public string DriverName { get; set; } // public Car() { } public Car(string name, int speed) { CurrentSpeed = speed; DriverName = name; } // public void Accelerate(int delta) { if (CarIsDead) { Console.WriteLine("Car is Dead"); } else { CurrentSpeed += delta; if (CurrentSpeed > MaxSpeed) { CarIsDead = true; CurrentSpeed = 0; throw new Exception(string.Format("Car drives too fast!")); // throw exception here } else Console.WriteLine("Ok"); } } } } |