Generate code for all exceptions thrown by the method

Do you know if there is any option or extension for generating the code needed to detect all exceptions thrown by a method in Visual Studio?

For example, I call File.WriteAllBytes(...)

This method can throw 9 Exceptions: System.ArgumentException, System.ArgumentNullException, etc. etc.

I want code for all 9 exceptions:

 catch (ArgumentException) { } catch (ArgumentNullException) { } ... 

I saw this behavior in Eclipse for Java, but I am wondering if there is anything like this in Visual Studio.

BTW I am using Visual Studio 2012 Premium

+6
source share
2 answers

There is nothing like this in Visual Studio.

The main problem is that unlike Java, C # does not support anything like the throws . Thus, there is no way to directly find out what possible exceptions a method might raise. The toolkit is built around a language feature that simply does not exist in C #.

Anders Halesberg discusses this decision in detail in this interview .

As they say, in C # you usually do not want to explicitly catch all these exceptions. You must catch exceptions that you can handle properly. If you want to catch all exceptions for registering puroses, just use one catch (Exception e) after any specific types of exceptions, and it will catch all other exceptions.

+14
source

C # is not Java. You not only do not need to catch all the exceptions thrown by the method, but also a very bad idea.

You should only catch exceptions that you need to handle. If there is nothing special in the specific exception that you need to do, then let it bubble up to your caller, who might have something he needs to do. Or it is not.

+3
source

Source: https://habr.com/ru/post/955695/


All Articles