Do you know if there is any option or extension to generate code required to catch all exceptions thrown by a method in Visual Studio?
For example I'm calling File.WriteAllBytes(...)
That method can throw 9 Exceptions: System.ArgumentException, System.ArgumentNullException, etc, etc.
I want the code for all 9 exceptions:
catch (ArgumentException) {
}
catch (ArgumentNullException) {
}
...
I have seen this behavior in Eclipse for Java but I wonder if there is anything similar in Visual Studio.
BTW I'm using Visual Studio 2012 Premium
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
You can have the possibility of throwing multiple different exceptions. For example: if (obj == null) throw new NullPointerException(); if (some other case) throw new IllegalArgumentException(); if (this == this) throw new IOException();
Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
The calculate method should check for an exception and if there is no exception, return the calculated value to the main function i.e. v1+v2 or v1-v2; Else if an exception exists then it should print the error statement and the value that is returned from the calculate method to the main method should be 0.0(Not ...
There is nothing like this in Visual Studio.
The main issue is, unlike Java, C# doesn't support anything like the throws
clause. As such, there is no way to directly know what possible exceptions a method will raise. The tooling is built around the language feature, which just doesn't exist in C#.
Anders Hejlsberg discusses this decision in detail in this interview.
That being said, in C#, you typically do not want to explicitly catch all of these exceptions. You should only catch the exceptions which you can handle properly. If you want to catch all exceptions for logging puroses, just use a single catch (Exception e)
after any specific exception types, and it will catch all other exceptions.
C# is not Java. Not only do you not need to catch all exceptions thrown by a method, it's also a very bad idea.
You should only catch exceptions that you need to handle. If there is nothing in particular that you need to do for a particular exception, then let it bubble up to your caller, which may have something that it needs to do. Or it may not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With