Exception handling in stored process, loop IF..ELSE
Hello Guys,
we want to put in exception handling in the loop but get the following error:
Error(43,3): PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: begin case declare end exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimited-identifier> <a bind variable> << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe
create or replace
PROCEDURE xxxx
FOR MESSSY IN
select I.*
FROM x I
LOOP
IF upper(CODE)='N' THEN
INSERT INTO T_MESS(MP)
select I.MP_ID
FROM T_ME
ELSIF upper(MESSSY.k2)='L' THEN
DELETE T_MESS WHERE T_MESS.MP = MESSSY.MP;
END IF;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
A program attempted to insert duplicate values in a column that is constrained by a unique index.
DBMS_OUTPUT.PUT_LINE ('A program attempted to insert duplicate values in a column that is constrained by a unique index.')
--No Rollback
END;
COMMIT;
END LOOP;
END xxxx;
does someone know why?
BluShadow wrote:
Well, your code is missing all sorts of bits and we don't have your data or your exact logic to know what it's supposed to be achieving.
That is right, you dont have my data and that is why I was suprised by your comment.
Since the input table might contain a few thousand rows and each of those might need to
be considered N , D, or C and each case has a different handling I can not imagine how this
can be all done with a merge statement.
MERGE
T_METRICPOINT_META with T_METRICSSYSTEM_LOAD where T_METRICSSYSTEM_LOAD .LOAD_DATE=to_char(sysdate)
WHEN MATCHED THEN --we know those are the metric points that have to be loaded today, but we still need to do a IF..ELSE to handle them
WHEN NOT MATCHED THEN -- not considered in todays load
----original code-----
create or replace
PROCEDURE myprocedure AS
BEGIN
--Extracting the records from T_METRICSSYSTEM_LOAD which have todays load date. Corresponding to these MP_System, we extract the MP_IDs from the T_METRICPOINT_META table.
--Comapring these MP_IDs with the MP_IDs from the source(T_METRICPOINT_IMPORT) and extracting only those Metric points which need to be loaded today.
FOR METRICSSYSTEM IN
select I.*
FROM T_METRICPOINT_IMPORT I
where I.LOADDATE = TO_CHAR(SYSDATE) AND I.MP_ID IN
(select a.MP_ID
from T_METRICPOINT_META a INNER JOIN T_METRICSSYSTEM_LOAD b on a.MP_SYSTEM = b.MP_SYSTEM where b.LOAD_DATE=to_char(sysdate))
LOOP
--If mutation code in the source/import data is "N", the record is inserted as it is in the "T_METRICPOINTS" table.
IF upper(METRICSSYSTEM.MUTATIONCODE)='N' THEN --new
INSERT INTO T_METRICPOINTS(MP_ID, ......)
SELECT DISTINCT I.MP_ID,.....
FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='D' THEN --delete
DELETE T_METRICPOINTS WHERE T_METRICPOINTS.MP_ID = METRICSSYSTEM.MP_ID AND T_METRICPOINTS.KEY = METRICSSYSTEM.KEY;
ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='C' THEN --correction
UPDATE T_HISTORYMETRICPOINTS H
SET CHANGE_DATE = to_char(sysdate)
WHERE H.MP_ID=METRICSSYSTEM.MP_ID AND H.KEY = METRICSSYSTEM.KEY;
INSERT INTO T_HISTORYMETRICPOINTS(MP_ID, KEY, .....)
--The distinct here is used, to handle 2 identical records in the input table with correction value "C". This would insert into 1 record in the T_HISTORYMETRICPOINTS table without
--violating the primary key constraint.
select DISTINCT I.MP_ID,I.KEY, ....
FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
--END IF;
END IF;
COMMIT;
END LOOP;
END myprocedure;
Similar Messages
-
Never implemented exception handling in Stored Procedures
I have lots of stand alone stored procedures callled from .NET 20 programs that follow the following pattern. They runn against Oracle 10.2 on Win2003. The only deviiation is a couple where I insert to temptables. I specify a parameter for messages but don't know the best way to implement for Oracle as well as any tips on ODP.NET/oracle interactions error handling.
1. Is it recommended to implement exception handling in With Clauses?
2. If there is an exception in one cursor's SQL, how do I still execute the second?
3. Is it best in some circumstances to pass a null back to client and check for null in program?
From .NET programs I have run into a couple of problems.
4. TNS packet failure.
Anyways any suggestions or experiences are welcome.
CREATE OR REPLACE PROCEDURE GET_SALES_DATA
, p_businessdate in date
, p_message out varchar2
, p_rcSales out sys_refcursor
, p_rInventory out sys_refcursor
) is
open p_rcSales for
with somedata as (select ...)
, someMoreData as (selct ...)
-- Main select
Select * from somedata sd inner join somemoredata smd on smd.key = sd.key;
open p_rcInventory for
with somedata as (select ...)
, someMoreData as (selct ...)
-- Main select
Select * from somedata sd inner join somemoredata smd on smd.key = sd.key;
-- CODE NOT IMPLEMENTED
-- exception
-- when TOO_MANY_ROWS then select 'Error handling for future implementations' into p_message from dual ;
-- when NO_DATA_FOUND then select 'Error handling for future implementations. No data' into p_message from dual;
-- when others then raise_application_error(-20011,'Unknown Exception in GET_SALES_DATA Function');
-- WHEN invalid_business_date then select 'Invalid: Business date is in the current work week.' into p_message from dual ;
END GET_SALES_DATA;Pseudocode'ish because Module level variables and properties have not been defined here for brevity.
Public Class WebPage1
PAge_Load
GetData
End Class Data Access Layer
Public Class DAL
Public Sub GetOracleData()
Dim conn As OracleConnection
Try
conn = New OracleConnection
Catch ex As Exception
Throw ex
End Try
Dim cmd As New OracleCommand
With cmd
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
cmd.CommandText = DATABASE.GetSalesData
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
End With
cmd.Connection = conn
Dim oparam As OracleParameter
oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
oparam.Value = BusinessDate.ToString("dd-MMM-yy")
oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rc_inven_csv", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
Dim Adapter As New OracleDataAdapter(cmd)
Try
Adapter.TableMappings.Add("Table", Sales)
Adapter.TableMappings.Add("Table1", Inventory)
Adapter.Fill(dsOracleData)
Catch ex As OracleException
HandleError("Exception Retrieving Oracle Data", ex, MethodInfo.GetCurrentMethod.Name, True)
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
dbMessages = cmd.Parameters("p_message").ToString
End If
arrStatusMessages.Add("Retrieved Oracle Data Successfully")
End Sub
' Original Implementation ; No longer used
Public function GetOracleData
Dim conn As New OracleConnection
conn.ConnectionString = dbconn.Connectionstring
Dim cmd As New OracleCommand
With cmd
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
cmd.CommandText = DATABASE.GetSalesData
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
End With
cmd.Connection = conn
Dim oparam As OracleParameter
oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
oparam.Value = BusinessDate.ToString("dd-MMM-yy")
oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
Dim Adapter As New OracleDataAdapter(cmd)
Try
Adapter.TableMappings.Add("Table", Sales)
Adapter.TableMappings.Add("Table1", Inventory)
Adapter.Fill(dsOracleData)
dim dt as datatable = dsoracledata.tables("sales")
If IsDataNull(dt) Then
_errorType = DBErrorType.NullData
End If
If isDataEmpty(dt) Then
_errorType = DBErrorType.EmptyData
End If
_hasError = False
Catch oraEx As OracleException
_ExceptionText = oraEx.Message.ToString
_errorType = DBErrorType.OracleException
#If DEBUG Then
Throw oraEx
#End If
Catch zeroEx As DivideByZeroException
_ExceptionText = zeroEx.Message.ToString
_errorType = DBErrorType.DivideByZeroException
#If DEBUG Then
Throw zeroEx
#End If
Catch oflowEx As OverflowException
_ExceptionText = oflowEx.Message.ToString
_errorType = DBErrorType.OverflowException
#If DEBUG Then
Throw oflowEx
#End If
Catch argEx As InsufficientMemoryException
_ExceptionText = argEx.Message.ToString
_errorType = DBErrorType.InsufficientMemoryException
#If DEBUG Then
Throw argEx
#End If
Catch nomemEx As OutOfMemoryException
_ExceptionText = nomemEx.Message.ToString
_errorType = DBErrorType.OutOfMemoryException
#If DEBUG Then
Throw nomemEx
#End If
Catch Ex As Exception
_ExceptionText = Ex.Message.ToString
_errorType = DBErrorType.GenericException
#If DEBUG Then
Throw Ex
#End If
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
End class Error Class
Public Class Errors
Public Sub ExitClass()
Return
End Sub
' 'blnWriteNow says when Error is critical and no further processing needs to be done by class, then write to event logs or text files and call exit class
' to return control back to webpage. This is my first time trying this way.
Public Sub HandleError(ByVal friendlyMsg As String, ByVal objEx As Exception, ByVal methodInfo As String, Optional ByVal blnWriteNow As Boolean = False)
If Not blnWriteNow Then Exit Sub
Dim strMessages As String
strMessages = arrStatusMessages
'Send error email
If blnSendEmails Then
SendMail("[email protected], strMessages. applicationname, " has thrown error. ")
End If
'Throw error for debugging
If blnThrowErrors Then
Throw New Exception(strMessages & vbCrLf & objEx.Message)
End If
' Write to event log and if not available (shared hosting environment), write to text log
If blnWriteNow Then
If blnWriteToEvtLog Then
If blnCanWriteToEvtLog Then 'Program has write permission to log
WriteToEventLog(strMessages, _appname, EventLogEntryType.Error, appname)
Else
If Not Directory.Exists( appPath & "\log") Then
Try
Directory.CreateDirectory( appPath & "\log")
Catch ex As Exception
arrStatusMessages.Add("Cant't write to event log or create a directory")
End Try
End If
End If
End If
End If
End Sub
End ClassI have lots of stand alone stored procedures callled from .NET 20 programs that follow the following pattern. They runn against Oracle 10.2 on Win2003. The only deviiation is a couple where I insert to temptables. I specify a parameter for messages but don't know the best way to implement for Oracle as well as any tips on ODP.NET/oracle interactions error handling.
1. Is it recommended to implement exception handling in With Clauses?
2. If there is an exception in one cursor's SQL, how do I still execute the second?
3. Is it best in some circumstances to pass a null back to client and check for null in program?
From .NET programs I have run into a couple of problems.
4. TNS packet failure.
Anyways any suggestions or experiences are welcome.
CREATE OR REPLACE PROCEDURE GET_SALES_DATA
, p_businessdate in date
, p_message out varchar2
, p_rcSales out sys_refcursor
, p_rInventory out sys_refcursor
) is
open p_rcSales for
with somedata as (select ...)
, someMoreData as (selct ...)
-- Main select
Select * from somedata sd inner join somemoredata smd on smd.key = sd.key;
open p_rcInventory for
with somedata as (select ...)
, someMoreData as (selct ...)
-- Main select
Select * from somedata sd inner join somemoredata smd on smd.key = sd.key;
-- CODE NOT IMPLEMENTED
-- exception
-- when TOO_MANY_ROWS then select 'Error handling for future implementations' into p_message from dual ;
-- when NO_DATA_FOUND then select 'Error handling for future implementations. No data' into p_message from dual;
-- when others then raise_application_error(-20011,'Unknown Exception in GET_SALES_DATA Function');
-- WHEN invalid_business_date then select 'Invalid: Business date is in the current work week.' into p_message from dual ;
END GET_SALES_DATA;Pseudocode'ish because Module level variables and properties have not been defined here for brevity.
Public Class WebPage1
PAge_Load
GetData
End Class Data Access Layer
Public Class DAL
Public Sub GetOracleData()
Dim conn As OracleConnection
Try
conn = New OracleConnection
Catch ex As Exception
Throw ex
End Try
Dim cmd As New OracleCommand
With cmd
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
cmd.CommandText = DATABASE.GetSalesData
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
End With
cmd.Connection = conn
Dim oparam As OracleParameter
oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
oparam.Value = BusinessDate.ToString("dd-MMM-yy")
oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rc_inven_csv", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
Dim Adapter As New OracleDataAdapter(cmd)
Try
Adapter.TableMappings.Add("Table", Sales)
Adapter.TableMappings.Add("Table1", Inventory)
Adapter.Fill(dsOracleData)
Catch ex As OracleException
HandleError("Exception Retrieving Oracle Data", ex, MethodInfo.GetCurrentMethod.Name, True)
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
dbMessages = cmd.Parameters("p_message").ToString
End If
arrStatusMessages.Add("Retrieved Oracle Data Successfully")
End Sub
' Original Implementation ; No longer used
Public function GetOracleData
Dim conn As New OracleConnection
conn.ConnectionString = dbconn.Connectionstring
Dim cmd As New OracleCommand
With cmd
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
cmd.CommandText = DATABASE.GetSalesData
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
End With
cmd.Connection = conn
Dim oparam As OracleParameter
oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
oparam.Value = BusinessDate.ToString("dd-MMM-yy")
oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
Dim Adapter As New OracleDataAdapter(cmd)
Try
Adapter.TableMappings.Add("Table", Sales)
Adapter.TableMappings.Add("Table1", Inventory)
Adapter.Fill(dsOracleData)
dim dt as datatable = dsoracledata.tables("sales")
If IsDataNull(dt) Then
_errorType = DBErrorType.NullData
End If
If isDataEmpty(dt) Then
_errorType = DBErrorType.EmptyData
End If
_hasError = False
Catch oraEx As OracleException
_ExceptionText = oraEx.Message.ToString
_errorType = DBErrorType.OracleException
#If DEBUG Then
Throw oraEx
#End If
Catch zeroEx As DivideByZeroException
_ExceptionText = zeroEx.Message.ToString
_errorType = DBErrorType.DivideByZeroException
#If DEBUG Then
Throw zeroEx
#End If
Catch oflowEx As OverflowException
_ExceptionText = oflowEx.Message.ToString
_errorType = DBErrorType.OverflowException
#If DEBUG Then
Throw oflowEx
#End If
Catch argEx As InsufficientMemoryException
_ExceptionText = argEx.Message.ToString
_errorType = DBErrorType.InsufficientMemoryException
#If DEBUG Then
Throw argEx
#End If
Catch nomemEx As OutOfMemoryException
_ExceptionText = nomemEx.Message.ToString
_errorType = DBErrorType.OutOfMemoryException
#If DEBUG Then
Throw nomemEx
#End If
Catch Ex As Exception
_ExceptionText = Ex.Message.ToString
_errorType = DBErrorType.GenericException
#If DEBUG Then
Throw Ex
#End If
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
End class Error Class
Public Class Errors
Public Sub ExitClass()
Return
End Sub
' 'blnWriteNow says when Error is critical and no further processing needs to be done by class, then write to event logs or text files and call exit class
' to return control back to webpage. This is my first time trying this way.
Public Sub HandleError(ByVal friendlyMsg As String, ByVal objEx As Exception, ByVal methodInfo As String, Optional ByVal blnWriteNow As Boolean = False)
If Not blnWriteNow Then Exit Sub
Dim strMessages As String
strMessages = arrStatusMessages
'Send error email
If blnSendEmails Then
SendMail("[email protected], strMessages. applicationname, " has thrown error. ")
End If
'Throw error for debugging
If blnThrowErrors Then
Throw New Exception(strMessages & vbCrLf & objEx.Message)
End If
' Write to event log and if not available (shared hosting environment), write to text log
If blnWriteNow Then
If blnWriteToEvtLog Then
If blnCanWriteToEvtLog Then 'Program has write permission to log
WriteToEventLog(strMessages, _appname, EventLogEntryType.Error, appname)
Else
If Not Directory.Exists( appPath & "\log") Then
Try
Directory.CreateDirectory( appPath & "\log")
Catch ex As Exception
arrStatusMessages.Add("Cant't write to event log or create a directory")
End Try
End If
End If
End If
End If
End Sub
End Class -
Exception handling in integration processes
Hi,
I have a very simple question but I can't find an answer. I have designed an integration process that upon several other things send synchroneously a message to an ABAP proxy. Sometime the ABAP proxy generates exception. In my integration process these exceptionx are catched in a specific branch.
My question is: how to access the data contained in the catched exception (message, text....)?
Regards,
Yann Le BlevecHello Yann,
There is no solution for your problem, I guess. I didnt try it on my own, but in my own research on sdn I found two experts positions to that issue:
"you cannot catch the exception's value in the XI "
(see posting from Michal Krawczyk, Jun 12, 2006, in thread catch the exception)
"The content of a fault message are not accessible inside a BPM."
(see posting from Bhavesh Kantilal, Oct 3, 2007, in thread Notify user about Exception in BPM)
Regards,
Dennis -
Is Exception handler necessary for every stored subprogram
Hi All,
I knwo exception handler is very important. But is it necessary for every stored procedure or function?
For example,
procedure test(p_index_code IN varchar2(10)
p_changed_code OUT varchar2(15))
as
begin
IF p_index_code = 'A' then
p_changed_code := 'A'|| p_index_code;
elsif p_index_code = 'B' then
p_changed_code := 'B'|| p_index_code;
else
p_changed_code := p_index_code;
end if;
end;
This kind of simple procedures, do I have to add the 'exection when others than raise_application_error(-20001,'error in this SP')'?
I can't see obvious drawbacks without the exception handler in this CASE.
Best regards,
Leon
Edited by: user12064076 on Nov 11, 2010 7:12 PMuser12064076 wrote:
I knwo exception handler is very important. But is it necessary for every stored procedure or function?It is important to know WHY an exception handler is needed. There are couple of basic reasons why you want to use an exception handler.
The exception is not an error.
The exception raised is a technical error, but may not be a business or processing error. The typical example is the NO_DATA_FOUND exception. The business logic may say "+when there is no fixed discounts found, apply a 5% dis-count+". So not finding (dis-count) row data in such a case is not an exception. What does you exception handler do? It fixes the exception and there is not an exception anymore. In other words, the caller that called your code will never know that there was an exception.
Making the exception meaningful
An exception, like NO_DATA_FOUND, is not very meaningful. What is meaningful is NO_INVOICE_FOUND or NO_CUSTOMER_FOUND. Thus your exception handler can catch a generic exception and make it more meaningful by returning a custom application exception instead.
Action stations
Some exceptions will require you to clean up and fix what you can - kind of like action stations when a ship takes a hit. But as you cannot fix the exception, the exception must be passed to the caller so that it too can decide how to re-act to that exception. For example, you may have an open ref cursor or open UTL_FILE handle that needs to be closed when your code terminates. If not, your code will leak resources. So you need to trap exceptions that can occur, clean up, and then re-raise the exception (this is called a resource protection code block in other languages). You may have done a partial transaction - and the exception handler may need to roll back the changes your code made. The bottom line here is that you must re-raise the exception after you have done your "+action stations+" bit. You did not fix the exception. You did not make it more meaningful. In that case you must pass it back to the caller so that it can decide what it needs to do about that exception.
Using an exception for any other reason - that would likely be the wrong thing to do most of the time. -
Add three stored procs in one big proc and add exception handling
I have three proc's,
1. sp_staging
2. sp_upload
3. sp_process.
Now, I have to create a new proc as sp_daily which has the other three proc's in it in the same order.
if the first proc sp_staging fails, then the sp_daily proc should stop executing the other proc's which are in the order.
CREATE PROCEDURE sp_daily
AS
BEGIN TRY
EXEC sp_staging (already has EXCEPTION handling IN it)
GO
EXEC sp_upload (already has EXCEPTION handling IN it)
GO
EXEC sp_process (already has EXCEPTION handling IN it)
GO
END TRY
BEGIN CATCH
-- If any of the above proc's fail, the next proc's should not be executed
END CATCH
Something like this????Hi naveej,
Whether the Stored Procedure sp_daily stops executing if the first sp_staging fails depends on how you code. To give a better demonstration, I will show the scenario that sp_upload runs with error. Please see the below code.
--create the scenario
USE master;
IF db_id('TestDB') IS NULL
CREATE DATABASE TestDB;
USE TestDB;
IF OBJECT_ID('T1') IS NOT NULL
DROP TABLE T1;
GO
CREATE TABLE T1
procName varchar(99)
IF OBJECT_ID('sp_staging') IS NOT NULL
DROP PROCEDURE "sp_staging";
GO
CREATE PROCEDURE "sp_staging" @denominator FLOAT
AS
BEGIN TRY
DECLARE @quotient FLOAT;
SET @denominator=1/@denominator; -- when @denominator=0, error occurs
INSERT INTO T1 VALUES('sp_staging finished');
END TRY
BEGIN CATCH
END CATCH
GO
IF OBJECT_ID('sp_upload') IS NOT NULL
DROP PROCEDURE "sp_upload";
GO
CREATE PROCEDURE "sp_upload" @denominator FLOAT
AS
BEGIN TRY
DECLARE @quotient FLOAT;
SET @denominator=1/@denominator;
INSERT INTO T1 VALUES('sp_upload finished');
END TRY
BEGIN CATCH
DECLARE @ERRMSG VARCHAR(99);
SELECT @ERRMSG=ERROR_MESSAGE()+'sp_upload failed, process continues';
INSERT INTO T1 VALUES(@ERRMSG);
END CATCH
GO
IF OBJECT_ID('sp_process') IS NOT NULL
DROP PROCEDURE "sp_process";
GO
CREATE PROCEDURE "sp_process" @denominator FLOAT
AS
BEGIN TRY
DECLARE @quotient FLOAT;
SET @denominator=1/@denominator;
INSERT INTO T1 VALUES('sp_process finished');
END TRY
BEGIN CATCH
END CATCH
GO
IF OBJECT_ID('sp_daily') IS NOT NULL
DROP PROCEDURE "sp_daily";
GO
CREATE PROCEDURE "sp_daily" @p1Deno FLOAT,@p2Deno FLOAT,@p3Deno FLOAT
AS
BEGIN TRY
EXEC sp_staging @p1Deno;
EXEC sp_upload @p2Deno;
EXEC sp_process @p3Deno;
END TRY
BEGIN CATCH
INSERT INTO T1 SELECT ERROR_MESSAGE()+'error captured by sp_daily';
END CATCH
GO
--Test Example
TRUNCATE TABLE T1;
EXEC sp_daily 1,0,1;
SELECT * FROM T1;
We can judge from the rows in T1, sp_daily continued even when there came a error in sp_upload. The reason for the continuity is that the error which occurred in sp_upload was caught and handled by sp_upload itself. Sp_daily's CATCH block didn't capture
any error(we didnt see any row like "error captured by sp_daily") so sp_dailys continued running with no interruption.
Let’s make a little modification on the sp_upload. see the below code.
ALTER PROCEDURE "sp_upload" @denominator FLOAT
AS
BEGIN TRY
DECLARE @quotient FLOAT;
SET @denominator=1/@denominator;
INSERT INTO T1 VALUES('sp_upload');
END TRY
BEGIN CATCH
DECLARE @ERRMSG VARCHAR(99),@ErrSeverity INT;
SELECT @ERRMSG=ERROR_MESSAGE()+'sp_upload failed, process got terminated',@ErrSeverity=ERROR_SEVERITY();
RAISERROR(@ERRMSG ,@ErrSeverity,1);
END CATCH
GO
--Test Example
TRUNCATE TABLE T1;
EXEC sp_daily 1,0,1;
SELECT * FROM T1;
At this time, sp_daily got terminated when sp_upload encountered an error. Sp_upload didn’t handle the error, it threw the error instead. Then the CATCH block in sp_daily caught the error and interrupted sp_daily itself. If you don’t
need to handle the error which may occur inside of the inner called procedures, the TRY and CATCH block in the procedure which calls them would be enough to catch and handle the errors anywhere it occurs, just remove the blocks from the called ones.
ALTER PROCEDURE "sp_staging" @denominator FLOAT
AS
DECLARE @quotient FLOAT;
SET @denominator=1/@denominator;
INSERT INTO T1 VALUES('sp_staging finished');
GO
ALTER PROCEDURE "sp_upload" @denominator FLOAT
AS
DECLARE @quotient FLOAT;
SET @denominator=1/@denominator;
INSERT INTO T1 VALUES('sp_upload finished');
GO
ALTER PROCEDURE "sp_process" @denominator FLOAT
AS
DECLARE @quotient FLOAT;
SET @denominator=1/@denominator;
INSERT INTO T1 VALUES('sp_process finished');
GO
ALTER PROCEDURE "sp_daily" @p1Deno FLOAT,@p2Deno FLOAT,@p3Deno FLOAT
AS
BEGIN TRY
EXEC sp_staging @p1Deno;
EXEC sp_upload @p2Deno;
EXEC sp_process @p3Deno;
END TRY
BEGIN CATCH
INSERT INTO T1 SELECT ERROR_MESSAGE();
END CATCH
GO
--Test Example
TRUNCATE TABLE T1;
EXEC sp_daily 1,0,1;
SELECT * FROM T1;
As we can see from the above modification, sp_daily calls sp_staging, sp_upload, sp_process in order. Sp_staging runs fine so it finishes. When it comes to sp_upload, error gets captured so the execution terminates. Anyway if you hope that the 3
called procedures work atomically(it is a pretty common business requirement), which means unless all of the three finish otherwise no one finishes, the TRAN block would help. Please see the below code.
ALTER PROCEDURE "sp_daily" @p1Deno FLOAT,@p2Deno FLOAT,@p3Deno FLOAT
AS
BEGIN TRY
BEGIN TRAN
EXEC sp_staging @p1Deno;
EXEC sp_upload @p2Deno;
EXEC sp_process @p3Deno;
COMMIT TRAN;
END TRY
BEGIN CATCH
ROLLBACK TRAN;
INSERT INTO T1 SELECT ERROR_MESSAGE();
END CATCH
GO
--Test Example
TRUNCATE TABLE T1;
EXEC sp_daily 1,0,1;
SELECT * FROM T1;
If you have question, feel free to let me know.
Best Regards,
Eric Zhang -
Exception Handling inside a Multi-Instance Loop
I would like to see a sample process that demonstrates Exception Handling inside an inline subprocess containing another subprocess with a multi-instance sub-process in parallel. The outer sub-process is executing in sequence. Each instance of the outer loop depends upon the outcome of the successful execution of previous step. At each step, the inner inline sub-process activity can have more than one instance which are all executed in parallel using multi-instance. If the outcome code of any one of these parallel instances is "REJECT" code, we simply raise a business exception and the stop the outer sub-process from going through the next instance of the loop. The problem we are trying to solve is similar to the sample in chapter 5 of the book "New Book: Oracle BPM Suite 11g: Advanced BPMN Topics" by Mark Nelson. Particularly, the exception handling example shown in Page 73 under the topic “Exception Handling with embedded Sub-processes”. The inner most multi-instance sub-process should raise a business exception and interrupt the .
We would like to see a smple that demonstrates how exceptions are handled inside a multi-instance parallel sub-process. Could someone please provide a working sample that we can go though? We would like to raise a business exception as soon as certain outcome of a Human Tasks in observed and break out of the loop and continue thereafter. Thanks very much in advance for your help.
Pankaj
Edited by: 1001027 on 2-May-2013 10:09 AMI would like to see a sample process that demonstrates Exception Handling inside an inline subprocess containing another subprocess with a multi-instance sub-process in parallel. The outer sub-process is executing in sequence. Each instance of the outer loop depends upon the outcome of the successful execution of previous step. At each step, the inner inline sub-process activity can have more than one instance which are all executed in parallel using multi-instance. If the outcome code of any one of these parallel instances is "REJECT" code, we simply raise a business exception and the stop the outer sub-process from going through the next instance of the loop. The problem we are trying to solve is similar to the sample in chapter 5 of the book "New Book: Oracle BPM Suite 11g: Advanced BPMN Topics" by Mark Nelson. Particularly, the exception handling example shown in Page 73 under the topic “Exception Handling with embedded Sub-processes”. The inner most multi-instance sub-process should raise a business exception and interrupt the .
We would like to see a smple that demonstrates how exceptions are handled inside a multi-instance parallel sub-process. Could someone please provide a working sample that we can go though? We would like to raise a business exception as soon as certain outcome of a Human Tasks in observed and break out of the loop and continue thereafter. Thanks very much in advance for your help.
Pankaj
Edited by: 1001027 on 2-May-2013 10:09 AM -
Integration Process exception handling & alerts, Java
Hello,
I would like to enhance my basic scenarios fool proof and with as much Java as possible.
I have set up several asynchronous and synchronous File to SOAP transfers between systems A and B
using PI70 including my own Java mapping classes and PI's AF_Modules beans. They work just fine.
I have not designed my own Integration Processes yet, so execution is based on channel settings and availability timing.
I have learned this aproach may be exposed to general faults resulting manual monitoring and repairing.
For example server problems at receiver side can result data losses as sender channel just keeps removing source
files like normally, as the process would be better to just stop right there and alert or something.
My question is, is the "Enterprise services Builders" Integration Process & Graphical definition screen the one and only tool to
customize whole process exception handling and alerts in PI, and Java is not an option?
Appreciate your advice on this.
Kind regards mHi m,
Strange Name
>>I have learned this aproach may be exposed to general faults resulting manual monitoring and repairing. For example server problems at receiver side can result data losses as sender channel just keeps removing source files like normally, as the process would be better to just stop right there and alert or something.
If you are looking to handle this particular scenario, then we have the alert mechanism and CCMS monitoring. There you will come to know whether the end system down or not.
Also in addition to this you can write your own java (in message mapping, as modules, java mapping) /abap code (as abap mapping, user exit in standard functions etc) for providing more details in error scenarios. But you need to validate whether the maintenance/development cost for the code is justified in your scenarios
Regards
Suraj -
BPM Process - Exception handling or timeout issues?
Hi Guys,
I have a BPM process as below.
1. Receive step: Receive the file with multiple transactions.
2. Transformation step: Split the file into individual transactions
3 Block step which includes -- par for each mode
1. Send Step (Synchronus): Each individual transaction needs to contact the 3rd party system and get the response. -- Do i need to handle any exceptions here ?
2. Container : Collect all the responses
Block ends
4. Transformation: combine all the responses in to a single file
5. Send Step: synchronus -- send the above single file and get the response back
6. Transformation : Transform the above response into the target structure.
7. Send: send the message asynchronusly to the target system
I need suggestion regarding the exceptional handling or any time out issues, i need to take care of.
any suggestions would be really appreciated
Thanks,
Raj
Edited by: raj reddy on Feb 12, 2009 10:12 PMHi,
I) For the Block holding the Sync Send, create an Exception Block. (right click on Sync Send -> Insert -> Exception Branch)
II) Name the Exception block (ex: exceptionHandler).
III) in the Sync Send step ->Properties -> Exceptions -> in System Error - add exceptionHandler.
IV) Now within the Exception handler block you can create containers to hold values from payload, throw exception as email etc).
This will cover your sync send step incase there is an error while sending the request of a timeout during receiving the response.
You can also do the same for the Step 7) Asycn send - if required.
Another suggestion in your question Step 6) can be done outside the bpm, when you do the interface determination for that Asycn Send you can add the Interface mapping that will map the responses to the target structure.
Doing this will reduce one step in your BPM. For further information in how more you can fine tune your bpm, read this blog - https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/5113. [original link is broken] [original link is broken] [original link is broken]
All the best.
Regards,
Balaji.M -
Exception Handling of Screenflows inside Processes
Greetings,
We are currently encountering a problem where some unhandled Exceptions are not being caught in our BPM application.
Whenever an exception occurs inside a process, BPM has provided a way of handling those exceptions by using the “Process Exception” activity (this looks like a small lightning bolt). All errors that are not caught but are of the compatible type would fall into this activity and get processed.
The problem arises when your process has a Global Activity Interactive Screenflow. Whenever this screenflow encounters an error inside its flow, it does not get caught by the “Process Exception” activity even though this process was the one that invoked it.
We can try to make some exception handling per automatic activity inside the Screenflow itself but this usually results in large try-catch statements and multiple connections to custom defined exception activities. This may not be the optimal solution to this.
Would anyone be able to shed some light on this or offer some best practices on how to resolve these issues?
Thank you very much!
Oracle BPM Suite 10.3.2Wish I had a better answer for you. Telling you something that you already know, but if you've defined the Global's property with "Has instance access" then you can catch the exceptions in the process.
Undoubtedly though, you've got a standalone Global or you would not be asking the question. The exception from a Global that does not have instance access can't get caught in the process because there was never an instance created for it inside the process. -
Resume process instance after exception handling with an event subprocess
We have a process with several automatic activities so we implement an event-based subprocess to catch any exception that occurs in the process.
Since the error event is an interrupting event, how could we control the exception and resume the process where it was?
BPM version 11.1.1.7
Any suggestion?
Thank youKnow this isn't the answer you are looking for, but the answer to this gets much better in 12c where you can go back into the process after catching an exception in an event subprocess.
In 11g however, once you catch an exception in an event subprocess you cannot go back where you left off in the main process.
These are not great options I know, but here are a couple things I've seen to work around this:
Exception error events in event subprocesses are always interrupting so one solution would be to instead use boundary events on the individual activities where the exceptions will occur. Know you know this, but the down side of this is that it makes your process incredibly cluttered with boundary events.
Catch the error in the event subprocess -> handle the cause of the exception -> exit the process -> invoke the process again. The problem with this is that you would not be starting where you left off and where the error occurred. You could work around this by having an exclusive gateway that directed it to the right activity in the process.
Dan -
Exception Handling for Array Binding
Hi
1)
I am using a Stored Procedure.
I am using array binding and if i am sending an array of count 10 to be inserted in a table and only 9 got inserted,i deliberatly inserted one errorneous record in array, the count returned by ExecuteNonQuery() is 10.Why ?
How can i come to know exact number of rows inserted in table, how can i use Output variables, because the array bind count is 10 so if i add an output parameter it gives error ArrayBind count is wrong....
2)
Is it possible to roll back all the inserts if error occurs in any of the insert by Oracle engine.What it does is it inserts all correct records and leaves the errorneous record and doesn't even throw any exception or any message.
Answer - This can be achieved by using OracleTransaction and don't use Exception handling in procedure otherwise there wont be any exception thrown by procedure which is necessary to detect if an error occured during insert.If you use exception handling OracleEngine will insert correct rows and leave errorneous record and return count of inserted + non inserted records which is wrong.
Please help.
Message was edited by:
user556446
Message was edited by:
user556446You'll need to encapsulate your validation within it's own block as described below:
-- this will die on the first exception
declare
TYPE T_BADDATA_TEST IS TABLE OF VARCHAR2(1000) INDEX BY binary_integer ;
tbt T_BADDATA_TEST ;
aBadTypeFound exception ;
begin
tbt(0) := 'a';
tbt(1) := 'b';
tbt(2) := 'c';
for idx in tbt.first..tbt.last loop
if tbt(idx) = 'b' then
raise aBadTypeFound ;
else
dbms_output.put_line(tbt(idx));
end if ;
end loop ;
end ;--encapsulate the exception area in a begin/end block to handle the exception but continue on
declare
TYPE T_BADDATA_TEST IS TABLE OF VARCHAR2(1000) INDEX BY binary_integer ;
tbt T_BADDATA_TEST ;
aBadTypeFound exception ;
begin
tbt(0) := 'a';
tbt(1) := 'b';
tbt(2) := 'c';
for idx in tbt.first..tbt.last loop
BEGIN
if tbt(idx) = 'b' then
raise aBadTypeFound ;
else
dbms_output.put_line(tbt(idx));
end if ;
EXCEPTION
WHEN aBadTypeFound THEN
dbms_output.put_line(tbt(idx) || ' is bad data');
WHEN OTHERS THEN
dbms_output.put_line('exception');
END ;
end loop ;
end ;
output:
a
b is bad data
c
***/ -
Good exception handling policy for Java web application
I'm looking for a good exception handling policy for Java web application. First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace();
Then I found this Oracle page The Message-Driven Bean Class - The Java EE 6 Tutorial, which does just that. So now I'm confused. Is there a good page online for an exception handling policy for Java EE Web applications? I have a hard time finding one. I've read that you should not catch the Exception class. I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop. We have a loop which runs once a minute implemented using the Quartz framework. Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.I'm looking for a good exception handling policy for Java web application.
If you have not done so I suggest you start by reviewing the several trails in The Java Tutorials.
Those trails cover both HOW to use exceptions and WHEN to use them.
This trail discusses the 'controversy' you mention regarding 'Unchecked Exceptions'
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Unchecked Exceptions — The Controversy
Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.
Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Generally don't catch an exception unless you plan to HANDLE the exception. Logging, by itself is NOT handliing.
First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace();
That article, like many, has some good advice and some poor or even bad advice. You get what you pay for!
I've read that you should not catch the Exception class.
Ok - but all that does is indicate that a problem of some sort happened somewhere. Not very useful info. Java goes to a lot of trouble to provide specific exceptions for specific problems.
I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop.
If the exception is 'unknown' then maybe it NEEDS to 'stop all other customers from executing later on in the loop'.
That is EXACTLY why you don't want to do that. You need to identify which exceptions should NOT stop processing and which ones should.
Some 'unknown' exceptions can NOT be recovered and indicate a serious problem, perhaps with the JVM itself. You can NOT just blindly keep executing and ignore them without risking data corruption and/or the integrity of the entire system Java is running on.
Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.
No - not if you want a well-behaved system.
Don't catch exceptions unless you HANDLE/resolve them. There are times when it makes sense to log the exception (which does NOT handle it) and then raise it again so that it gets handled properly later. Yes - I know that is contrary to the advice given in that article but, IMHO, that article is wrong about that point.
If you have ever had to maintain/fix/support someone else's Java code you should already understand how difficult it can be to find WHERE a problem occurs and WHAT the exact problem is when exceptions are not handled properly. -
PL/SQL 101 : Exception Handling
Frequently I see questions and issues around the use of Exception/Error Handling in PL/SQL. More often than not the issue comes from the questioners misunderstanding about how PL/SQL is constructed and executed, so I thought I'd write a small article covering the key concepts to give a clear picture of how it all hangs together. (Note: the examples are just showing examples of the exception handling structure, and should not be taken as truly valid code for ways of handling things)
Exception Handling
Contents
1. Understanding Execution Blocks (part 1)
2. Execution of the Execution Block
3. Exceptions
4. Understanding Execution Blocks (part 2)
5. How to continue exection of statements after an exception
6. User defined exceptions
7. Line number of exception
8. Exceptions within code within the exception block
1. Understanding Execution Blocks (part 1)
The first thing that one needs to understand is almost taking us back to the basics of PL/SQL... how a PL/SQL execution block is constructed.
Essentially an execution block is made of 3 sections...
+---------------------------+
| Declaration Section |
+---------------------------+
| Statements Section |
+---------------------------+
| Exception Section |
+---------------------------+
The Declaration section is the part defined between the PROCEDURE/FUNCTION header or the DECLARE keyword (for anonymous blocks) and the BEGIN keyword. (Optional section)
The Statements section is where your code goes and lies between the BEGIN keyword and the EXCEPTION keyword (or END keyword if there is no EXCEPTION section). (Mandatory section)
The Exception section is where any exception handling goes and lies between the EXCEPTION keyword at the END keyword. (Optional section)
Example of an anonymous block...
DECLARE
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
Example of a procedure/function block...
[CREATE OR REPLACE] (PROCEDURE|FUNCTION) <proc or fn name> [(<parameters>)] [RETURN <datatype>] (IS|AS)
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
(Note: The same can also be done for packages, but let's keep it simple)
2. Execution of the Execution Block
This may seem a simple concept, but it's surprising how many people have issues showing they haven't grasped it. When an Execution block is entered, the declaration section is processed, creating a scope of variables, types , cursors, etc. to be visible to the execution block and then execution enters into the Statements section. Each statment in the statements section is executed in turn and when the execution completes the last statment the execution block is exited back to whatever called it.
3. Exceptions
Exceptions generally happen during the execution of statements in the Statements section. When an exception happens the execution of statements jumps immediately into the exception section. In this section we can specify what exceptions we wish to 'capture' or 'trap' and do one of the two following things...
(Note: The exception section still has access to all the declared items in the declaration section)
3.i) Handle the exception
We do this when we recognise what the exception is (most likely it's something we expect to happen) and we have a means of dealing with it so that our application can continue on.
Example...
(without the exception handler the exception is passed back to the calling code, in this case SQL*Plus)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
(with an exception handler, we capture the exception, handle it how we want to, and the calling code is happy that there is no error for it to report)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9 exception
10 when no_data_found then
11 dbms_output.put_line('There is no employee with this employee number.');
12* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
There is no employee with this employee number.
PL/SQL procedure successfully completed.
3.ii) Raise the exception
We do this when:-
a) we recognise the exception, handle it but still want to let the calling code know that it happened
b) we recognise the exception, wish to log it happened and then let the calling code deal with it
c) we don't recognise the exception and we want the calling code to deal with it
Example of b)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16* end;
SQL> /
Enter value for empno: 123
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 15
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
Example of c)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16 WHEN others THEN
17 RAISE;
18* end;
SQL> /
Enter value for empno: 'ABC'
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 'ABC';
declare
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 3
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
As you can see from the sql_errors log table, no log was written so the WHEN others exception was the exception that raised the error to the calling code (SQL*Plus)
4. Understanding Execution Blocks (part 2)
Ok, so now we understand the very basics of an execution block and what happens when an exception happens. Let's take it a step further...
Execution blocks are not just a single simple block in most cases. Often, during our statements section we have a need to call some reusable code and we do that by calling a procedure or function. Effectively this nests the procedure or function's code as another execution block within the current statement section so, in terms of execution, we end up with something like...
+---------------------------------+
| Declaration Section |
+---------------------------------+
| Statements Section |
| . |
| +---------------------------+ |
| | Declaration Section | |
| +---------------------------+ |
| | Statements Section | |
| +---------------------------+ |
| | Exception Section | |
| +---------------------------+ |
| . |
+---------------------------------+
| Exception Section |
+---------------------------------+
Example... (Note: log_trace just writes some text to a table for tracing)
SQL> create or replace procedure a as
2 v_dummy NUMBER := log_trace('Procedure A''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure A''s Statement Section');
5 v_dummy := 1/0; -- cause an exception
6 exception
7 when others then
8 v_dummy := log_trace('Procedure A''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> create or replace procedure b as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 a; -- HERE the execution passes to the declare/statement/exception sections of A
6 exception
7 when others then
8 v_dummy := log_trace('Procedure B''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> exec b;
BEGIN b; END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.B", line 9
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Procedure A's Declaration Section
Procedure A's Statement Section
Procedure A's Exception Section
Procedure B's Exception Section
6 rows selected.
SQL>
Likewise, execution blocks can be nested deeper and deeper.
5. How to continue exection of statements after an exception
One of the common questions asked is how to return execution to the statement after the one that created the exception and continue on.
Well, firstly, you can only do this for statements you expect to raise an exception, such as when you want to check if there is no data found in a query.
If you consider what's been shown above you could put any statement you expect to cause an exception inside it's own procedure or function with it's own exception section to handle the exception without raising it back to the calling code. However, the nature of procedures and functions is really to provide a means of re-using code, so if it's a statement you only use once it seems a little silly to go creating individual procedures for these.
Instead, you nest execution blocks directly, to give the same result as shown in the diagram at the start of part 4 of this article.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure b (p_empno IN VARCHAR2) as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 -- Here we start another execution block nested in the first one...
6 declare
7 v_dummy NUMBER := log_trace('Nested Block Declaration Section');
8 begin
9 v_dummy := log_trace('Nested Block Statement Section');
10 select empno
11 into v_dummy
12 from emp
13 where empno = p_empno; -- Note: the parameters and variables from
parent execution block are available to use!
14 exception
15 when no_data_found then
16 -- This is an exception we can handle so we don't raise it
17 v_dummy := log_trace('No employee was found');
18 v_dummy := log_trace('Nested Block Exception Section - Exception Handled');
19 when others then
20 -- Other exceptions we can't handle so we raise them
21 v_dummy := log_trace('Nested Block Exception Section - Exception Raised');
22 raise;
23 end;
24 -- ...Here endeth the nested execution block
25 -- As the nested block handled it's exception we come back to here...
26 v_dummy := log_trace('Procedure B''s Statement Section Continued');
27 exception
28 when others then
29 -- We'll only get to here if an unhandled exception was raised
30 -- either in the nested block or in procedure b's statement section
31 v_dummy := log_trace('Procedure B''s Exception Section');
32 raise;
33* end;
SQL> /
Procedure created.
SQL> exec b(123);
PL/SQL procedure successfully completed.
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
No employee was found
Nested Block Exception Section - Exception Handled
Procedure B's Statement Section Continued
7 rows selected.
SQL> truncate table code_trace;
Table truncated.
SQL> exec b('ABC');
BEGIN b('ABC'); END;
ERROR at line 1:
ORA-01722: invalid number
ORA-06512: at "SCOTT.B", line 32
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
Nested Block Exception Section - Exception Raised
Procedure B's Exception Section
6 rows selected.
SQL>
You can see from this that, very simply, the code that we expected may have an exception was able to either handle the exception and return to the outer execution block to continue execution, or if an unexpected exception occurred then it was able to be raised up to the outer exception section.
6. User defined exceptions
There are three sorts of 'User Defined' exceptions. There are logical situations (e.g. business logic) where, for example, certain criteria are not met to complete a task, and there are existing Oracle errors that you wish to give a name to in order to capture them in the exception section. The third is raising your own exception messages with our own exception numbers. Let's look at the first one...
Let's say I have tables which detail stock availablility and reorder levels...
SQL> select * from reorder_level;
ITEM_ID STOCK_LEVEL
1 20
2 20
3 10
4 2
5 2
SQL> select * from stock;
ITEM_ID ITEM_DESC STOCK_LEVEL
1 Pencils 10
2 Pens 2
3 Notepads 25
4 Stapler 5
5 Hole Punch 3
SQL>
Now, our Business has told the administrative clerk to check stock levels and re-order anything that is below the re-order level, but not to hold stock of more than 4 times the re-order level for any particular item. As an IT department we've been asked to put together an application that will automatically produce the re-order documents upon the clerks request and, because our company is so tight-ar*ed about money, they don't want to waste any paper with incorrect printouts so we have to ensure the clerk can't order things they shouldn't.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 begin
11 OPEN cur_stock_reorder;
12 FETCH cur_stock_reorder INTO v_stock;
13 IF cur_stock_reorder%NOTFOUND THEN
14 RAISE no_data_found;
15 END IF;
16 CLOSE cur_stock_reorder;
17 --
18 IF v_stock.stock_level >= v_stock.reorder_level THEN
19 -- Stock is not low enough to warrant an order
20 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
21 ELSE
22 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
23 -- Required amount is over-ordering
24 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
25 ELSE
26 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
27 -- Here goes our code to print the order
28 END IF;
29 END IF;
30 --
31 exception
32 WHEN no_data_found THEN
33 CLOSE cur_stock_reorder;
34 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
35* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
Ok, so that code works, but it's a bit messy with all those nested IF statements. Is there a cleaner way perhaps? Wouldn't it be nice if we could set up our own exceptions...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 --
11 -- Let's declare our own exceptions for business logic...
12 exc_not_warranted EXCEPTION;
13 exc_too_much EXCEPTION;
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 RAISE exc_not_warranted;
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29 RAISE exc_too_much;
30 END IF;
31 --
32 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
33 -- Here goes our code to print the order
34 --
35 exception
36 WHEN no_data_found THEN
37 CLOSE cur_stock_reorder;
38 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
39 WHEN exc_not_warranted THEN
40 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
41 WHEN exc_too_much THEN
42 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
43* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
That's better. And now we don't have to use all those nested IF statements and worry about it accidently getting to code that will print the order out as, once one of our user defined exceptions is raised, execution goes from the Statements section into the Exception section and all handling of errors is done in one place.
Now for the second sort of user defined exception...
A new requirement has come in from the Finance department who want to have details shown on the order that show a re-order 'indicator' based on the formula ((maximum allowed stock - current stock)/re-order quantity), so this needs calculating and passing to the report...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 begin
16 OPEN cur_stock_reorder;
17 FETCH cur_stock_reorder INTO v_stock;
18 IF cur_stock_reorder%NOTFOUND THEN
19 RAISE no_data_found;
20 END IF;
21 CLOSE cur_stock_reorder;
22 --
23 IF v_stock.stock_level >= v_stock.reorder_level THEN
24 -- Stock is not low enough to warrant an order
25 RAISE exc_not_warranted;
26 END IF;
27 --
28 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
29 -- Required amount is over-ordering
30 RAISE exc_too_much;
31 END IF;
32 --
33 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
34 -- Here goes our code to print the order, passing the finance_factor
35 --
36 exception
37 WHEN no_data_found THEN
38 CLOSE cur_stock_reorder;
39 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
40 WHEN exc_not_warranted THEN
41 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
42 WHEN exc_too_much THEN
43 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
44* end;
SQL> /
Procedure created.
SQL> exec re_order(2,40);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL> exec re_order(2,0);
BEGIN re_order(2,0); END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.RE_ORDER", line 17
ORA-06512: at line 1
SQL>
Hmm, there's a problem if the person specifies a re-order quantity of zero. It raises an unhandled exception.
Well, we could put a condition/check into our code to make sure the parameter is not zero, but again we would be wrapping our code in an IF statement and not dealing with the exception in the exception handler.
We could do as we did before and just include a simple IF statement to check the value and raise our own user defined exception but, in this instance the error is standard Oracle error (ORA-01476) so we should be able to capture it inside the exception handler anyway... however...
EXCEPTION
WHEN ORA-01476 THEN
... is not valid. What we need is to give this Oracle error a name.
This is done by declaring a user defined exception as we did before and then associating that name with the error number using the PRAGMA EXCEPTION_INIT statement in the declaration section.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 --
16 exc_zero_quantity EXCEPTION;
17 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
18 begin
19 OPEN cur_stock_reorder;
20 FETCH cur_stock_reorder INTO v_stock;
21 IF cur_stock_reorder%NOTFOUND THEN
22 RAISE no_data_found;
23 END IF;
24 CLOSE cur_stock_reorder;
25 --
26 IF v_stock.stock_level >= v_stock.reorder_level THEN
27 -- Stock is not low enough to warrant an order
28 RAISE exc_not_warranted;
29 END IF;
30 --
31 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
32 -- Required amount is over-ordering
33 RAISE exc_too_much;
34 END IF;
35 --
36 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
37 -- Here goes our code to print the order, passing the finance_factor
38 --
39 exception
40 WHEN exc_zero_quantity THEN
41 DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
42 WHEN no_data_found THEN
43 CLOSE cur_stock_reorder;
44 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
45 WHEN exc_not_warranted THEN
46 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
47 WHEN exc_too_much THEN
48 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
49* end;
SQL> /
Procedure created.
SQL> exec re_order(2,0);
Quantity of 0 (zero) is invalid.
PL/SQL procedure successfully completed.
SQL>
Lastly, let's look at raising our own exceptions with our own exception numbers...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 exc_zero_quantity EXCEPTION;
13 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 [b]RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached re-order level yet!');[/b]
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29its nice article, have put up this one the blog
site,Nah, I don't have time to blog, but if one of the other Ace's/Experts wants to copy it to a blog with reference back to here (and all due credit given ;)) then that's fine by me.
I'd go for a book like "Selected articles by OTN members" or something. Does anybody have a list of links of all those mentioned articles?Just these ones I've bookmarked...
Introduction to regular expressions ... by CD
When your query takes too long ... by Rob van Wijk
How to pipeline a function with a dynamic number of columns? by ascheffer
PL/SQL 101 : Exception Handling by BluShadow -
11g ADF TaskFlow Exception Handling in BPM
Hi Guys
BPM 11g
I have a human task that is implemented as an ADF task flow. I would like to be able to throw an exception from the ADF application and have it handled by the BPM process, does anyone know if this is possible or how I would do that?
At the moment I have an ADF error page - I could return an "error" outcome to the process from that but an error is an error and it feels right to show that in the process instead of a normal outcome.
anyone else worked through this?
cheers,
Stevehelp yourself with this thread - Re: Exception Handling
it should answer your question -
FORALL Exception handling problem
Hi All,
I have one doubt in forall exception handling. I have gone through the SAVE EXCEPTION for bulk collect but i have one more query
BEGIN
FORALL j IN l_tab.first .. l_tab.last
INSERT INTO exception_test
VALUES (l_tab(i));
EXCEPTION
END;
My requirement is when an exception occurs, i ant to print the values of the collection.
e.g. say l_tab (j).emp_number, l_tab (j).emp_id.
How is that possible?
Thanks
Samarth
Edited by: 950810 on Mar 12, 2013 7:28 PM>
I have one doubt in forall exception handling. I have gone through the SAVE EXCEPTION for bulk collect but i have one more query
BEGIN
FORALL j IN l_tab.first .. l_tab.last
INSERT INTO exception_test
VALUES (l_tab(i));
EXCEPTION
END;
My requirement is when an exception occurs, i ant to print the values of the collection.
e.g. say l_tab (j).emp_number, l_tab (j).emp_id.
How is that possible?
>
Post the code you are using. You didn't post the FORALL that is using SAVE EXCEPTIONS.
The SQL%BULK_EXCEPTIONS associative array that you get has the INDEX of the collection element that caused the exception.
So you need to use those indexes to index into the original collection to get whatever values are in it.
One index from the exception array is:
SQL%BULK_EXCEPTIONS(i).error_index So if your original collection is named 'myCollection' you would reference that collection value as:
myCollection(SQL%BULK_EXCEPTIONS(i).error_index); See 'Handling FORALL Exceptions (%BULK_EXCEPTIONS Attribute)' in the PL/SQL Language doc
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/tuning.htm#i49099
>
All exceptions raised during the execution are saved in the cursor attribute %BULK_EXCEPTIONS, which stores a collection of records. Each record has two fields:
%BULK_EXCEPTIONS(i).ERROR_INDEX holds the iteration of the FORALL statement during which the exception was raised.
%BULK_EXCEPTIONS(i).ERROR_CODE holds the corresponding Oracle Database error code.
The values stored by %BULK_EXCEPTIONS always refer to the most recently executed FORALL statement. The number of exceptions is saved in %BULK_EXCEPTIONS.COUNT. Its subscripts range from 1 to COUNT.
The individual error messages, or any substitution arguments, are not saved, but the error message text can looked up using ERROR_CODE with SQLERRM as shown in Example 12-9.
You might need to work backward to determine which collection element was used in the iteration that caused an exception. For example, if you use the INDICES OF clause to process a sparse collection, you must step through the elements one by one to find the one corresponding to %BULK_EXCEPTIONS(i).ERROR_INDEX. If you use the VALUES OF clause to process a subset of elements, you must find the element in the index collection whose subscript matches %BULK_EXCEPTIONS(i).ERROR_INDEX, and then use that element's value as the subscript to find the erroneous element in the original collection.
Maybe you are looking for
-
How to store a bitmap file in the table
i am using oracle 8i. i dont know how to save the bitmap file in the table, is long raw datatype should be used. thanks
-
Error while running jBoss server from console
I am facing a problem regarding running of Jboss server,When i am giving the run.bat command from my console a lot of lines of code is being displayed rapidly and the cursor is coming to a halt after giving the following message"[Error,Default] at ja
-
I'm writing a device driver for a custom PCI device and need 200+ MBytes/Sec through the PCI bus. I am using an Ultra450 with one of its 64 bit/66Mhz busses (528Mbytes/sec). Problem is that the bridge chip disconnects when each 64 byte boundary is cr
-
Oh Lord, I have a Powerbook 520c!!
While tossing out old electronic stuff, I discovered that I still have a PowerBook 520c, complete with that wild 4-prong power adapter. Heavy little sucker! I have no idea what is on it, but I'm sure it still works. It looks pretty cherry to be ho
-
Get rid of Java applet window box
We are currently using TTA 4.0 for Intel Linux Kernel. When bring up applications through the TTA, a "Java applet window" box is attached to the bottom of each applications. Is there a way to get rid of the box? Thanks Henry