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

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.

Related

eiffel: a statement for explicitly executing code when assertions are on

Sometimes the checks and contract constructions need an elaboration which wants to be avoided when assertions removed to improve performances and avoid doing useless things with the "only" work of the compiler. I refer for ex. to job in loops checks or other things. Sometimes having to build a function or having to think how to build it without being executed when assertions are on goes away of the intuitive way of the contract and its sense. I refer particularly to the check structure
Is there a way to do something such as
if checks_are_enabled then
do check stuff here
end
do_some_normal_job
if checks_are_enabled then
do other check stuff here
end
Assertions can be turned on and off on a class-by-class basis, with different levels: preconditions, postconditions, invariants, etc. As a result, it would be tricky and unreliable to report when they are enabled or not (consider, for example, inherited code: the checks might be on in one case and off in another). On a methodological level it would also break the idea that a correct program works the same way regardless of assertion monitoring.
What are workarounds?
If assertions are complex, they can be factored out to dedicated queries and look like
check
is_valid: complex_query
end
An alternative is to use debug statements:
debug ("check_this", "check_that")
... some complex code, including assertions
end
where "check_this" and "check_that" are debug keys that can be turned on when compiling for debugging.
There are hacks that could work now, but not in the future:
If a complex state needs to be computed and then checked after some operation, it can be saved in an object passed to some function with complex calculations and used later again:
check
is_valid_before: valid_pre (state) -- The state is computed by `valid_pre`.
end
code_that_does_the_work
check
is_valid_after: valid_post (state) -- The state is checked by `valid_post`.
end
Some global flag can be used to keep track about assertion monitoring:
check
is_monitoring_checks
end
where query is_monitoring_checks has side effects:
is_monitoring_checks: BOOLEAN
-- Record whether assertion checks are turned on.
do
is_check_on := True
Result := True
end
Then, subsequent code could be written as asked in the question:
if is_check_on then
... -- Do some complex calculations when assertions are turned on.
end

AppleScript not looping all numbers when using repeat

I am using this script to close all "Alerts" in my notification bar:
tell application "System Events"
tell process "NotificationCenter"
set numwins to (count windows)
repeat with i from numwins to 1 by -1
click button "Close" of window i
end repeat
end tell
end tell
However this doesn't close them all, even when there are no "Alert without Close button".
try catch didn't help. What's wrong?
I tested your script and it seemed to run correctly on my machine, but there is always a potential for problems when you use a repeat loop on a mutating list: in other words, a list that changes as the repeat loop progresses. Each time you close a window Notification Center changes its window list and updates the properties of the remaining windows; the script can simply lose track. I'm a little surprised it doesn't throw errors when this happens, but...
You can try this code and see if it works. rather than referring to windows by index it repeatedly tries to close the last window, ignoring any errors, and keeps on until the window count is zero or it loops 100 times (that last is to prevent an endless loop in case something goes wrong).
tell application "System Events"
tell process "NotificationCenter"
repeat 100 times
try
tell last window
click button "Close"
end tell
end try
if (count of its windows) = 0 then
exit repeat
end if
end repeat
end tell
end tell
EDIT
Per comments, the above doesn't work quite as advertised, so let's switch it over to AppleScriptObjC:
use framework "Foundation"
property NSUserNotificationCenter : class "NSUserNotificationCenter"
NSUserNotificationCenter's defaultUserNotificationCenter's removeAllDeliveredNotifications()
This seems to do the trick on my machine. Of course, NSUserNotificationCenter is deprecated as of 10.14, so this won't work forever — eventually you'll have to shift over to the notification's framework — but it should work for a few more OS versions.
EDIT 2
Per another comment, anyone working on os 10.14 or later (Mojave and Catalina, to date) can do an equivalent AppleScriptObjC routine using the UserNotifications framework, like so:
use framework "UserNotifications"
set notificationCenter to class "UNUserNotificationCenter"'s currentNotificationCenter
notificationCenter's removeAllDeliveredNotifications()
Note that I've used a slightly different syntax (merely calling class "UNUserNotificationCenter" rather than setting up a property). Both work; the property syntax is only preferable when you need to pass the class to handlers.

Breakable loop in Scratch?

How do you make a breakable loop in Scratch? I'm using Scratch 2.0 and can't find any good way to make a loop breakable, from inside of the loop itself.
Disclaimer:
There is no perfect way to do it. If you can possibly stand this true fact then feel free to continue.
There are a few different ways you could do it.
With repeat until
The first and most simple one follows this:
But this isn't technically part of the script - it's just repeating until some value returns true.
With a custom block (stop this script)
In order to do it inside of the script, you'll need to use a sneaky little trick with custom blocks.
Create a custom block called whatever you want - but probably along the lines of "breakable loop". Inside of it, create this script:
By using stop script we are breaking out of the script that is currently running - which, according to Scratch, is the custom block.
See the result! (as scratchblocks)
With broadcast and wait
You could also use a broadcast-and-wait method, very similar to above:
Though I highly suggest you don't use this method, as if any other sprites have breakable loops you'll need to rename each one, which can be tedious after using a lot of loops in a lot of sprites!
(Note this bug has been fixed in version 442 of the editor and such the following no longer applies.)
Help! My project is lagging a bunch now!
As #foi has noticed, if your code must be run inside of a frame you probably checked run without screen refresh. Unfortunately, due to a bug in the Scratch player, this causes the program to essentially break after the stop this script block has been activated. How can you handle this?
It follows the same principle you use when you use a run without screen refresh custom block inside of a forever loop - the loop doesn't use screen refresh while the inside does, allowing for instant animations whether or not one is using turbo mode.
Here's an example - the image is really too long to be embedded, so see it here instead.
You can make a variable inside or outside of the repeat and make your script like this:
repeat until [[my variable] = [e.g: 1]]
your code
your code
your code
your code
end of repeat until
For a "repeat until" block the simplest way would be to "or" your normal until condition with the break condition in the until.
By adding an incremeting loop counter variable in the loop you can use a "repeat until" to replicate the function of a "repeat n times" block
By using a "repeat until" block with only your break condition you get the equivalent of a "forever" block
If you need another script/ sprite to trigger the break then a public variable will let you break the loop from anywhere and let a single condition break loops for different sprites.
I'd post an image of the blocks but this is my first reply and the site won't let me!
good luck
You can use these few ways to do it...
conditional loop
stop this script
if then else, in the else section, put nothing
I would prefer to use the first method, as it requires less blocks and for the first method, you can still add in code that will be executed after the loop has stopped executing.
You can make it repeat x times or make it have a certain point where it stops, such as another variable changing.
Otherwise, I don't think there is a wat to do that.
Use the repeat until block. Then put in an equals block or whatever into the boolean part. Then inside that repeat until block, put a stop this script block.
Hope this helps :D

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

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)

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.

Resources