MSVS C# fastest way to remove try-catch blocks? - try-catch

I took over an incomplete project and to my utter disbelieve, every single function is wrapped with try-catch statements in this same format:
try
{
// work work.
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, ...);
}
As I search SO for a method to quickly remove all these try-catch blocks, I find that people are actually looking for method to automatically wrap their functions with try-catch! hmmm... Is that good programming practice at all? Is there is method to remove all blocks instead so that it makes debugging easier and allows me to really solve the exceptions?

You can change the option here:
Debug -> Exceptions -> CLR Exceptions -> Check the "Thrown" checkbox.
This causes the compiler to break whenever an exception is thrown, before checking any catch blocks.

This is a horrible programming practice. I once saw this as a bug mess up someone's database.
It is my firm opinion you are better off letting your program die a fiery death than mindlessly continue on in an unknown state.
I would do a find and replace on MessageBox.Show(ex with throw //MessageBox.Show(ex and replace them all. You will have to manually find the ones that should really be there and put them back.

Visual Studio's Regex search is pretty powerful, however it is a bit tricky to use, here is something that you might find useful in searching for your above code: (Note in the find dialog box, in the Options section choose "Use: Regular Expressions")
Will find your bad catches:
catch.*\n+:b+{[.:b\n]MessageBox.[.:b\n]*}
If you want to do a straight replace with a throw:
catch\n{\nthrow;\n}

I've discovered a solution to this for VB.NET.
Replace this:
\s(?<!End )Try((.|\r\n)+?)Catch(.|\r\n)+?(Finally((.|\r\n)+?)End Try|End Try)
...with this:
$1$5
It will remove the entire try/catch block while leaving behind only what was in the try and finally blocks. It doesn't work with nested try/catches, though, so you'd need to replace the nested blocks first and then the outer blocks last.

Quick and dirty trick:
search & replace try -> if(true) //WAS TRY
search & replace catch§ -> if(true) //WAS CATCH §
§ is a placeholder for the regex to match what is catched and put it after the comment WAS CATCH
by this way you can:
revert searching WAS TRY and WAS CATCH §
decide what has to be replaced and what has not when during rhe search
I use to comment with // DUMMY every catch that is temporary during the debug session.
(since this is a very old post, I didn't take all the time needed to write the regex etc... please be patient)

Related

The point of throwing exceptions

What's the point of throwing exceptions?
For example I stumbled across this:
static List<Integer> list(int [] a) {
if (a == null)
throw new NullPointerException();
//...
But when you don't throw the nullpointer, you'll also get a nullpointer?
I see this regularly and I wanted to know if this is a good habit to learn?
It's better to fail fast. For example the function could do a bunch of stuff before it even references the variable "a" in your example resulting in a lot of unnecessary processing.. It would be best just to fail immediately if you know "a" is null from the very beginning. You could also append a custom error message to the exception as well.
The idea behind the THROW is to prevent the error from stopping your program.
If it's a fatal enough error, your program will stop anyway. But if the program can continue it will, and just let you know that an error occurred.
In many cases, you assign a function to report the error, since you threw it up and know what it is.
I always found throwing exceptions to be a matter of design and readability. For example, generally when I design something I prefer to handle errors where they occur. However an equally valid design would be to throw the exception and handle it somewhere else. I have seen some abstractions where generally your flow is something similar to this...
FlowControl -> GenericMethod(catches exceptions and calls methods only) -> PrivateMethods (generally used to do the work, throws exceptions).
You might find a more complete answer here as well: When to catch the Exception vs When to throw the Exceptions?
It's possible that the rest of your method will not throw the exception and will instead have some kind of undesirable behavior if you use a null pointer. In your example, if it's basically a "ToList" wrapper, it might be implemented as:
static List<Integer> list(int[] a)
{
List<int> ret = new List<int>();
foreach (int i in a)
ret.add(i);
return ret;
}
Instead of throwing, this will simply return an empty list (if I recall correctly at least, I don't think C# throws on null lists used in foreach). As such, you'll need to include an explicit null check and throw to get your desired behavior.
Throwing specific exception means that your application has faced something it shouldn't have. It can be either invalid argument(when someone passes null and current method cannot work with value of null), invalid field state(its value has been changed to some value, which is forbidden for instance current state) and many many more.
Basically when you throw exceptions in a good manner, each person using your e.g. library can preserve its correct flow.

Wondering about qooxdoo syntax/parsing

I found two lines in my code.
test = new qx.ui.form.RadioGroup;
I am wondering, if the missing () might cause issues or should maybe raise a warning in the generator or the lint job.
qx.ui.form.RadioGroup;
I think it might be worth reporting it as a "statement without effect" in lint.
mck89's comment is the answer (I wonder why so many people put valid answers in comments...):
You don't need the parens, and new qx.ui.form.RadioGroup is a syntactically correct expression, equivalent to adding a pair of empty parens. (There are some checkers that will warn about this, like I believe JsLint, but qooxdoo doesn't ... :).
In your particular case, the code will also run successfully in the browser, as RadioGroup permits empty constructor args; you can use .add() later to add items to the group.

Why does Real Studio Break on the Catch of an Exception?

I have a try-catch block like this:
Try
Listbox1.RemoveRow(Listbox1.ListIndex)
Catch err As OutOfBoundsException
MsgBox("Derp")
End Try
When I run my project in the debugger I get an OutOfBoundsException on the exact line I was trying to catch! Why doesn't this work?!?
Seems to me like the debugger will break at that line and show you the exception. But if you hit resume, it will continue, catch the exception, and then display the message.
Maybe they changed the behavior of the debugger with this release.
Update: You can go to Project > Break on exception to change this
The debugger will break as soon as the exception is encountered, before any other code gets executed. This includes any exception handling code you may have put in like a Try...Catch block.
If you have a bit of code that raises a lot of exceptions and you'd rather not have to step through it every single time you debug, you have two options: nuclear and surgical.
The nuclear option is to tell the debugger to NOT break on any exceptions at all, which has the unfortunate side effect of applying to your entire project instead of the small portion of it you're excepting on.
The surgical option is to use pragma directives to toggle breaking on exceptions off and on around the troublesome code:
#Pragma BreakOnExceptions Off
try
Listbox1.RemoveRow Listbox1.ListIndex
catch err As OutOfBoundsException
MsgBox "Derp"
End
#Pragma BreakOnExceptions On
This is much more preferable then simply turning off part of the debugger altogether. Note: the BreakOnExepctions directive will revert to you global setting (on or off) as soon as the function returns and is local to the code it surrounds.

When to use assert() and when to use try catch?

In which situations do you use them?
Try... catch - for exceptional conditions, i.e. conditions which aren't caused by malformed code, but which may just alter the normal control flow by external unpredictable events.
Assertions for catching invalid code, i.e. checking if an invariant is held in the function, checking if an internal method is called with right arguments (for public API you might still want an exception for that), etc.
Those are my basic guidelines, but the conventions vary from situation to situation and from language to language.
When you're in doubt, you can ask yourself: is that specific safety check supposed to still be there in the release code, after we test and finish everything? If you answer "yes, it's still neccessary then", you probably want an exception. Otherwise, you probably want an assertion.
Normally assert() does not work in release code, so it can never replace a try-catch strategy. Nevertheless I like to use assert() in places where exceptions are thrown. For me (as a developer!), it is often more convenient to get by an assert() message to the line of failure than through the exception stack.
They are created for different purposes. Assert is more for finding bugs, try-catch is for handling exceptional situations.
The situations of try-catch and assert are totally different.
Assert is used to check if the value you have received, as parameter for example, is expected. I would not recommend to use assert in production code, it is used in unit-test mostly and rarely to check the parameters.
To check the passed values better to use something like:
public void test(int i) {
if (i < 0) {
throw new IllegalArgumentException("i cannot be less than 0");
}
...
}
Try-catch block is used when you know something inside the block can go wrong. For example, you write to an sdcard and there is no space for writing. Or, it happened that you try to read the array out of it bounds. Then, you put your critical code in try-catch block and check for the excpetions:
try {
InputStream is = new FileInputStream("filename.txt");
...
} catch FileNotFoundExcpetion {
System.out.println("file not found");
} finally {
...
}
More about exceptions and try-catch blocks.

How do I implement exceptions with nestable try-catch-finally statement with messages in C

I'm looking to implement exceptions with nestable try-catch-finally statement with messages in C using longjmp/setjmp.
I've managed to implement try-catch-else exceptions, they are not nestable. I'm also hoping to add messages to the exceptions. Any idea how I might be able to do it?
Dave Hanson has already done a really nice package of exception macros as part of his excellent book C Interfaces and Implementations. You could either use the code wholesale or learn from his techniques. For anyone who does a fair amount of C programming, the book is worth buying—it will change the way you change about C programming, and it will show you how to do object-oriented design in C.
For nesting: a stack-frame of current try/catch blocks.
Your try will be using setjmp to save to a jmpbuffer (I guess). If you've done a try, and hence are now in the scope of a try block and hit another try then you want to preserve the existing jmpbuffer and also create a new one - Push - and when catching you are longjmp-ing back to the point of the most recent try hence you Pop the latest jmpbuffer. So I think a stack-like model make sense for nested try/catch.
For implementation, I guess the simplest apporach is to reserve an array of jmpbuffers, hence limiting your try catch depth - but keeping it simple; Push and Pop just require you to track the index in that array.
For messages and other exception contents, a reserved area for "currentException".
Exception content. Keep it simple, define an Exception struct. A char array and an int. Keeping it simple, but not too simple, reserve an array of them so that you can support chaining.
For a throw you allow
throw ( "string", errcode )
Which simply zeros the array structure and makes one entry. And
catch ( exception )
Now can look in the array and finds the first entry, and then
throwChain ( "string", errcode)
Which adds the new exception to the array (if there is room, and if not can shuffle the array according some rule such as FIFO)
But, I've got to ask, why not just use C++?
Well, you cannot really implement exceptions in C since they are not supported by the language. The best you can do is emulate them using setjmp and longjmp and some diabolically clever macros.
A quick search turns up these links that may be useful to you:
Exceptions in C
Exception handling with longjmp()

Resources