Try and catch alternative - error-handling

Is there an alternative to Try and Catch in AutoIt? I wonder if there is something similar.

There exists no try-catch-construct in AutoIt. You have to use the #error macro:
call_your_function_here()
If #error Then
;do your error stuff
Else
;do your program stuff
EndIf

Related

Is there a bgerror hook equivalent for uncaught errors out of the event loop in TCL?

In Tcl, when an uncaught error occurs in the background in the event loop, the function bgerror will be called if one exists (or any function registered via interp bgerror).
When an unknown command is encountered, the unknown command will be called.
Is there a similar mechanism for uncaught errors outside of the event loop that make their way to the top level? The default behavior from tclsh is just to print the error on stderr, but I would like a specific proc to be called instead without having to put the entire code in one big catch.
The default behaviour, if a Tcl error makes it's way to the top of the main execution path, is to print the errorInfo trace to standard error and, if running as a script, exit with a non-zero result code. If you want to override this, you need to either write your own entry code/main loop in C (when you can do anything you want when Tcl_Eval() returns TCL_ERROR), or wrap your code in a catch or try. You can use uplevel #0 within such Tcl code to ensure that the trapping code doesn't appear to be on the stack as seen by the rest of your code.
For example:
proc printStackOnError {script} {
try {
uplevel "#0" $script
} on error {msg opt} {
set stackinfo [dict get $opt -errorinfo]
# remove last three uninteresting lines; they're just part of this procedure's machinery
puts stderr [join [lrange [split $stackinfo "\n"] 0 end-3] "\n"]
}
}
Demonstrating (interactively, with Tcl 8.6):
% printStackOnError {eval {error foo}}
foo
while executing
"error foo"
("eval" body line 1)
invoked from within
"eval {error foo}"
You're advised to make sure you either print or log the errorInfo when an error is trapped at that level. Otherwise any bugs in your code are going to be unreasonably difficult to fix.

Stop SAS EG project if error is encountered

I tried putting this before all programs (using the option to include code in pre-processing):
OPTIONS ERRORABEND;
It does trigger a warning popup but the next files do get executed. For example:
A -­> B -> C -> D
If A has an error, I will get a popup saying that an error occured and that the server has disconnected, however, B, C, and D will also run. I want the project execution to stop at A.
I have several old projects with tens if not hundreds of programs and therefore I don't consider using a macro (Is there a way to make SAS stop upon the first warning or error?) while also checking for errors as an option.
What can be done?
Thank you!
Edit: This is for SAS Entreprise Guide 7.1
I think the best way is to write in Macro, like:
%Macro error_check;
'your process for A';
%if &syserr > 0 %then %do;
%goto exit;
%end; /* if your systemerror value is greater than zero, then go to exit directly */
'your process for B';
'your process for C';
'your process for D';
%exit: /* be careful, it is not semicolon*/
%Mend;
Just try NOT to put that %if &syserr loop inside a "data-run statement". I tried to do that and things got just complicated.

How does "if xx > 0then" execute but not compile?

I've got a PL/SQL-Block which looks like this:
declare
L_Count number := 10;
begin
if L_Count > 0then
dbms_output.put_line('l_Count > 0');
else
dbms_output.put_line('l_Count <= 0');
end if;
exception
when others then
dbms_output.put_line('exception occurred');
end;
Note the fourth line containing 0then instead of 0 then.
Using PL/SQL-Developer, I can execute this block as an SQL statement, which actually outputs l_Count > 0. Using a "Program Window" and compiling this, PL/SQL-Developer says the following error:
Unable to perform operation due to errors in source code
How can this statement execute but not compile?
Thank you for your hints!
The behavior is not what I would expect either. However, both the PL/SQL Developer SQL Window and Command Window modes execute this consistently with how SQL*Plus behaves. So, this is either:
Not a bug, or
An Oracle bug but not an Allround Automations bug.
Execution and compilation are two separate things. The code block is an anonynous block and it cannot be compiled. However you can execute the block. Execution would show you l_Count > 0.
Thanks,
Aditya

How to catch the error on screen into variable in TCL using catch

To grep the error on the screen though catch eg
puts $c
#error on terminal : can't read "c": no such variable
catch {puts $c} err
puts $err # value of err 1
Is there any way to catch actual error message in
TCL apart from signal in variable err.
Yes. Read the ::errorInfo or ::errorCode global variables to get the stack trace and a machine-parsable "POSIX error" three-element list, correspondingly.
Since Tcl 8.5, it's also possible to pass a name of a dictionary to catch after the name of the variable to receive the result, and that dictionary will be populated by much of what can be obtained via "classic" error variables I described above, and more.
This is all explained in the catch manual page.

SQL Server - stop or break execution of a SQL script

Is there a way to immediately stop execution of a SQL script in SQL server, like a "break" or "exit" command?
I have a script that does some validation and lookups before it starts doing inserts, and I want it to stop if any of the validations or lookups fail.
The raiserror method
raiserror('Oh no a fatal error', 20, -1) with log
This will terminate the connection, thereby stopping the rest of the script from running.
Note that both severity level 20 or higher and the WITH LOG option are necessary for it to work this way.
This even works with GO statements, eg.
print 'hi'
go
raiserror('Oh no a fatal error', 20, -1) with log
go
print 'ho'
Will give you the output:
hi
Msg 2745, Level 16, State 2, Line 1
Process ID 51 has raised user error 50000, severity 20. SQL Server is terminating this process.
Msg 50000, Level 20, State 1, Line 1
Oh no a fatal error
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.
Notice that 'ho' is not printed.
CAVEATS:
This only works if you are logged in as admin ('sysadmin' role), and also leaves you with no database connection.
If you are NOT logged in as admin, the RAISEERROR() call itself will fail and the script will continue executing.
When invoked with sqlcmd.exe, exit code 2745 will be reported.
Reference: http://www.mydatabasesupport.com/forums/ms-sqlserver/174037-sql-server-2000-abort-whole-script.html#post761334
The noexec method
Another method that works with GO statements is set noexec on (docs). This causes the rest of the script to be skipped over. It does not terminate the connection, but you need to turn noexec off again before any commands will execute.
Example:
print 'hi'
go
print 'Fatal error, script will not continue!'
set noexec on
print 'ho'
go
-- last line of the script
set noexec off -- Turn execution back on; only needed in SSMS, so as to be able
-- to run this script again in the same session.
Just use a RETURN (it will work both inside and outside a stored procedure).
If you can use SQLCMD mode, then the incantation
:on error exit
(INCLUDING the colon) will cause RAISERROR to actually stop the script. E.g.,
:on error exit
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SOMETABLE]') AND type in (N'U'))
RaisError ('This is not a Valid Instance Database', 15, 10)
GO
print 'Keep Working'
will output:
Msg 50000, Level 15, State 10, Line 3
This is not a Valid Instance Database
** An error was encountered during execution of batch. Exiting.
and the batch will stop. If SQLCMD mode isn't turned on, you'll get parse error about the colon. Unfortuantely, it's not completely bulletproof as if the script is run without being in SQLCMD mode, SQL Managment Studio breezes right past even parse time errors! Still, if you're running them from the command line, this is fine.
I would not use RAISERROR- SQL has IF statements that can be used for this purpose. Do your validation and lookups and set local variables, then use the value of the variables in IF statements to make the inserts conditional.
You wouldn't need to check a variable result of every validation test. You could usually do this with only one flag variable to confirm all conditions passed:
declare #valid bit
set #valid = 1
if -- Condition(s)
begin
print 'Condition(s) failed.'
set #valid = 0
end
-- Additional validation with similar structure
-- Final check that validation passed
if #valid = 1
begin
print 'Validation succeeded.'
-- Do work
end
Even if your validation is more complex, you should only need a few flag variables to include in your final check(s).
In SQL 2012+, you can use THROW.
THROW 51000, 'Stopping execution because validation failed.', 0;
PRINT 'Still Executing'; -- This doesn't execute with THROW
From MSDN:
Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct ... If a TRY…CATCH construct is not available, the session is ended. The line number and procedure where the exception is raised are set. The severity is set to 16.
I extended the noexec on/off solution successfully with a transaction to run the script in an all or nothing manner.
set noexec off
begin transaction
go
<First batch, do something here>
go
if ##error != 0 set noexec on;
<Second batch, do something here>
go
if ##error != 0 set noexec on;
<... etc>
declare #finished bit;
set #finished = 1;
SET noexec off;
IF #finished = 1
BEGIN
PRINT 'Committing changes'
COMMIT TRANSACTION
END
ELSE
BEGIN
PRINT 'Errors occured. Rolling back changes'
ROLLBACK TRANSACTION
END
Apparently the compiler "understands" the #finished variable in the IF, even if there was an error and the execution was disabled. However, the value is set to 1 only if the execution was not disabled. Hence I can nicely commit or rollback the transaction accordingly.
You can alter the flow of execution using GOTO statements:
IF #ValidationResult = 0
BEGIN
PRINT 'Validation fault.'
GOTO EndScript
END
/* our code */
EndScript:
you could wrap your SQL statement in a WHILE loop and use BREAK if needed
WHILE 1 = 1
BEGIN
-- Do work here
-- If you need to stop execution then use a BREAK
BREAK; --Make sure to have this break at the end to prevent infinite loop
END
Further refinig Sglasses method, the above lines force the use of SQLCMD mode, and either treminates the scirpt if not using SQLCMD mode or uses :on error exit to exit on any error
CONTEXT_INFO is used to keep track of the state.
SET CONTEXT_INFO 0x1 --Just to make sure everything's ok
GO
--treminate the script on any error. (Requires SQLCMD mode)
:on error exit
--If not in SQLCMD mode the above line will generate an error, so the next line won't hit
SET CONTEXT_INFO 0x2
GO
--make sure to use SQLCMD mode ( :on error needs that)
IF CONTEXT_INFO()<>0x2
BEGIN
SELECT CONTEXT_INFO()
SELECT 'This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!'
RAISERROR('This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!',16,1) WITH NOWAIT
WAITFOR DELAY '02:00'; --wait for the user to read the message, and terminate the script manually
END
GO
----------------------------------------------------------------------------------
----THE ACTUAL SCRIPT BEGINS HERE-------------
I use RETURN here all the time, works in script or Stored Procedure
Make sure you ROLLBACK the transaction if you are in one, otherwise RETURN immediately will result in an open uncommitted transaction
Is this a stored procedure? If so, I think you could just do a Return, such as "Return NULL";
Wrap your appropriate code block in a try catch block. You can then use the Raiserror event with a severity of 11 in order to break to the catch block if you wish. If you just want to raiserrors but continue execution within the try block then use a lower severity.
TRY...CATCH (Transact-SQL)
None of these works with 'GO' statements. In this code, regardless of whether the severity is 10 or 11, you get the final PRINT statement.
Test Script:
-- =================================
PRINT 'Start Test 1 - RAISERROR'
IF 1 = 1 BEGIN
RAISERROR('Error 1, level 11', 11, 1)
RETURN
END
IF 1 = 1 BEGIN
RAISERROR('Error 2, level 11', 11, 1)
RETURN
END
GO
PRINT 'Test 1 - After GO'
GO
-- =================================
PRINT 'Start Test 2 - Try/Catch'
BEGIN TRY
SELECT (1 / 0) AS CauseError
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS ErrorMessage
RAISERROR('Error in TRY, level 11', 11, 1)
RETURN
END CATCH
GO
PRINT 'Test 2 - After GO'
GO
Results:
Start Test 1 - RAISERROR
Msg 50000, Level 11, State 1, Line 5
Error 1, level 11
Test 1 - After GO
Start Test 2 - Try/Catch
CauseError
-----------
ErrorMessage
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Divide by zero error encountered.
Msg 50000, Level 11, State 1, Line 10
Error in TRY, level 11
Test 2 - After GO
The only way to make this work is to write the script without GO statements. Sometimes that's easy. Sometimes it's quite difficult. (Use something like IF #error <> 0 BEGIN ....)
you can use RAISERROR.
This was my solution:
...
BEGIN
raiserror('Invalid database', 15, 10)
rollback transaction
return
END
You can use GOTO statement. Try this. This is use full for you.
WHILE(#N <= #Count)
BEGIN
GOTO FinalStateMent;
END
FinalStatement:
Select #CoumnName from TableName
Thx for the answer!
raiserror() works fine but you shouldn't forget the return statement otherwise the script continues without error! (hense the raiserror isn't a "throwerror" ;-)) and of course doing a rollback if necessary!
raiserror() is nice to tell the person who executes the script that something went wrong.
If you are simply executing a script in Management Studio, and want to stop execution or rollback transaction (if used) on first error, then the best way I reckon is to use try catch block (SQL 2005 onward).
This works well in Management studio if you are executing a script file.
Stored proc can always use this as well.
Enclose it in a try catch block, then the execution will be transfered to catch.
BEGIN TRY
PRINT 'This will be printed'
RAISERROR ('Custom Exception', 16, 1);
PRINT 'This will not be printed'
END TRY
BEGIN CATCH
PRINT 'This will be printed 2nd'
END CATCH;
Back in the day we used the following...worked best:
RAISERROR ('Error! Connection dead', 20, 127) WITH LOG
Many thanks to all the other people here and other posts I have read.
But nothing was meeting all of my needs until #jaraics answered.
Most answers I have seen disregard scripts with multiple batches. And they ignore dual usage in SSMS and SQLCMD. My script is fully runable in SSMS -- but I want F5 prevention so they don't remove an existing set of objects on accident.
SET PARSEONLY ON worked well enough to prevent unwanted F5. But then you can't run with SQLCMD.
Another thing that slowed me down for a while is how a Batch will skip any further commands when there is an error - so my SET NOCOUNT ON was being skipped and thus the script still ran.
Anyway, I modified jaraics' answer just a bit: (in this case, I also need a database to be active from commandline)
-----------------------------------------------------------------------
-- Prevent accidental F5
-- Options:
-- 1) Highlight everything below here to run
-- 2) Disable this safety guard
-- 3) or use SQLCMD
-----------------------------------------------------------------------
set NOEXEC OFF -- Reset in case it got stuck ON
set CONTEXT_INFO 0x1 -- A 'variable' that can pass batch boundaries
GO -- important !
if $(SQLCMDDBNAME) is not null
set CONTEXT_INFO 0x2 -- If above line worked, we're in SQLCMD mode
GO -- important !
if CONTEXT_INFO()<>0x2
begin
select 'F5 Pressed accidentally.'
SET NOEXEC ON -- skip rest of script
END
GO -- important !
-----------------------------------------------------------------------
< rest of script . . . . . >
GO
SET NOEXEC OFF
print 'DONE'
I have been using the following script and you can see more details in my answer here.
RAISERROR ( 'Wrong Server!!!',18,1) WITH NOWAIT RETURN
print 'here'
select [was this executed]='Yes'