The question is the following code `

try { int a=int.Parse(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine(ex.Message); }` 

Is there a way not to prescribe try catch every time, but to override the behavior of System.FormatException so that it displays a message on the screen, for example, rather than throwing it out of the program?

  • four
    Especially for this are added safe implementations of the same - TryParse - Monk
  • one
    Yeah, and if another place in the code also uses System.FormatException , then there should suddenly be an exception throw? Such an approach would be suitable for small programs, but it does not work at all for any large-scale projects. - VladD

3 answers 3

Option 1. For a global solution within the entire application - at the start, we initialize the interception of exceptions:

 namespace myApp { static class Program { static void Main(string[] args) { Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); // здесь запускаемся... } } } 

in the method we process the interrupt:

  static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { if (e.Exception as System.FormatException != null) { //TODO что-то Console.WriteLine(ex.Message); } } 

Option 2. We can duplicate the TryParce mentioned above, but with our own implementation:

 public static class MyParseClass { public static bool Parse(object inParam, out outParam) { try { outParam=int.Parse(Console.ReadLine()); return true; } catch (Exception ex) { outParam = 0; Console.WriteLine(ex.Message); return false; } } } 

    .NET uses the exception mechanism to handle errors, this is not changed in any way, but in your case, you can write the code itself in a different way, for example, so that the user enters the number until it does it correctly:

     int a; while(!int.TryParse(Console.ReadLine(), out a)) { Console.WriteLine("Веденное значение не число, повторите ввод"); } Console.WriteLine(a); 

      For good in this situation, you need to handle exceptions of a certain type.

       try { //Делаем что-то } catch(FormatException ex) { //Делаем что-то другое } 
      • It is understandable, but if I declare a set of variables in different places, is there a way not to prescribe this each time? Using the method is not an option, it also clutters the code. - Faradey Inimicos
      • 2
        @FaradeyInimicos how does using method clutter up code? In general, a reasonable solution is to bring this into the method, and at least there are exceptions with logging, although TryParse is vitidev