Public exception handler in database package
I'm working on Oracle 10 g; I have a package with 10 functions, instead of writing exception for each individually is there is a way to do the same exception handler in all without repeating the exception handler in the 10 function (my exception handler is the same for the 10 function)
It would depend on how you are using the functions, and what exactly your exception handler does.
If, for example, your handler for no_data_found does a specific select statement, then you could put this statement in another function and call that function in the exception handler of each of the 10 functions. Note that you would need to catch the exception in eacg function, but the common code would be in one place. Something like:
FUNCTION error_func RETURN NUMBER IS
BEGIN
SELECT other_stuff INTO var;
RETURN var;
END;
function1 RETURN NUMBER IS;
BEGIN
SELECT stuff INTO var;
RETURN var;
EXCEPTION
WHEN NO_DATA_FOUND
effor_func;
END;
function2 RETURN NUMBER IS;
BEGIN
SELECT stuff INTO var;
RETURN var;
EXCEPTION
WHEN NO_DATA_FOUND
effor_func;
END;
function3 RETURN NUMBER IS;
BEGIN
SELECT stuff INTO var;
RETURN var;
EXCEPTION
WHEN NO_DATA_FOUND
effor_func;
END;If you always run all 10 functions in sequence, then you could make a wrapper to call the functions, and catch exceptions in the wrapper. Something along the lines of:
FUNCTION wrapper RETURN NUMBER IS;
BEGIN
function1;
function2;
function10;
EXCEPTION
WHEN NO_DATA_FOUND THEN
do something;
END;As constructed here, the wrapper wil not know which function errored nor will it continue running the other functions after getting an error.
John
Similar Messages
-
Exception handling in App. package PeopleCode
Hi,
I am accessing a table that is on remote database using DBLink for an update/insert operation using SQLExec. I am trying to implement exception handling to account for the scenario where the remote database is offline so that transaction can continue. However when I use the try-catch block in the app. package PeopleCode somehow the processing does not seem to move forward from the error. The App. pacakage code is triggered by the handler of the service operation. The goal is to simply skip the SQLExec if the table is not available. I am not sure if there is any limitation to the fatal SQL errors which the try-catch can handle.
As expected i get below error when running select on a view which has remote table in the SQL developer as remote database is down.
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
Has anyone enconutered similar issue with exception handling and best way to move forward in this scenario.
Any response is much appreciated.
Thanks,
GireeshI did this with PL/SQL once. Basically, you want to know if the remote database is available before you execute SQL against it. Here is my function. You can then SQLExec something like select 'x' from dual where my_package.link_available('the_link_name') = 1. If you get a result, then the db link is active. If you don't, it is not active.
FUNCTION LINK_AVAILABLE(pv_name VARCHAR2)
RETURN NUMBER AS
lv_result PLS_INTEGER;
lv_name VARCHAR2(128);
BEGIN
lv_name := UPPER(pv_name);
-- parameter check to avoid SQL injection with dynamic SQL below
-- if the following selects no rows, it will fall through to exception
-- and return 0;
SELECT 1
INTO lv_result
FROM ALL_DB_LINKS
WHERE DB_LINK = lv_name;
-- if we made it this far, then the parameter was a valid db link name
-- execute SQL to test
EXECUTE IMMEDIATE 'SELECT 1 FROM PS_INSTALLATION@' || lv_name INTO lv_result;
RETURN lv_result;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END LINK_AVAILABLE; -
Exception Handling in packages called from forms
I am running 10g forms that have many calls to packages/procedures in the database. I am seeing hanging processes on the web server (even after forms processes are stopped) and 1 of the causes Oracle listed was not having proper exception handling in the procesdures. Do I need to add an Exception (' when others then null') to my package specs to handle this?
"Do I need to add an Exception (' when others then null') to my package specs to handle this? "
That will hide the problem not handle it. You really need is to find out where the code is failing...
There is a method for logging message for debugging here...
http://oracle-developer.net/display.php?id=424
An another which is less good for a live system (the one above lets you set different levels of importance for logs messages and can be turned on or off for each user) but looks easier to implement in case you might be in a hurry...
Re: Zdebug -- Download a Forms debugging message tool -
Database package for handling SQL queries using JDBC/ODBC bridge
I perform a package using J2ME which can stores the contact.It consisting of the fascilities of the editing,Inserting, Deleting,Updating records
i have write import statements as
import javax.microedition.midlet*;
import javax.microedition.lcdui.*;
but when i write import java.sql.* error message shown AS this package does not exist.
So for J2ME using J2ME wireless toolkit 2.5 cldc which package i want to import to implement the sql statements i implement the Database using the text Files.
Requirement is that all SQL statements are implemented.also Which other equivalent packages are there for handling the databases in J2ME.
Please tell me all the package & Answer of the above problem.Hey
I was told that I can (through Java code) read all the registered DSNs and that way basically modify my application to populate it with a list of databases in the system and then when the user clicks on a database, the program would function as before...i.e. read the list of tables with it..yadda yadda yadda
Can anyone guide me on how to do that? read a list of DSNs in the system etc -
Database Exception Handling Error
Hi
Platform: BPEL/SOA Suite 10.1.3.3
I created an async BPEL process that does a simple insert into a database, and added error handling to ensure that database errors are trapped and interested parties notified when errors occur. To test the exception handling, I created a dummy table with an id and value column, where the value is declared as varchar2(1). Then I invoked the BPEL process with a string value longer than 1 character.
I expected to have the process catch the error, execute a java embedded System.out.println, assign the fault details to a fault variable string, and then terminate, with the terminated process displayed in the BPEL Console. Much to my surprise, as this executed perfectly in BPEL 10.1.2, this did not happen. Instead, the java embedded System.out.println executed, but then the following error was generated and the BPEL process was sent to the Manual Recovery area.
2007-10-18 10:52:29,879> <ERROR> <default.collaxa.cube.ws> <Database Adapter::Outbound> <oracle.tip.adapter.db.DBInteraction executeOutboundWrite> unable to execute the outbound insert operation on: DBAccessDummyTable.TestDummy
<2007-10-18 10:52:29,879> <ERROR> <default.collaxa.cube.ws> <AdapterFramework::Outbound> file:/E:/product/10.1.3.1/OracleAS_1/bpel/domains/default/tmp/.bpel_Test_DummyTable_Async_1.5_709050a551839440870cf17aba79c0f7.tmp/DBAccess_DummyTable.wsdl [ DBAccess_DummyTable_ptt::insert(TestDummyCollection,TestDummyCollection) ] - Could not invoke operation 'insert' against the 'Database Adapter' due to:
ORABPEL-11616
DBWriteInteractionSpec Execute Failed Exception.
insert failed. Descriptor name: [DBAccessDummyTable.TestDummy]. [Caused by: ORA-12899: value too large for column "ALE_ADAPTER"."TEST_DUMMY"."DUMMY_STRING_VALUE" (actual: 4, maximum: 1)
Caused by Exception [TOPLINK-4002] (Oracle TopLink - 10g Release 3 (10.1.3.3.0) (Build 070608)): oracle.toplink.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: ORA-12899: value too large for column "ALE_ADAPTER"."TEST_DUMMY"."DUMMY_STRING_VALUE" (actual: 4, maximum: 1)
Error Code: 12899
Call:INSERT INTO TEST_DUMMY (DUMMY_ID, DUMMY_STRING_VALUE) VALUES (?, ?)
bind => [280, long]
Query:InsertObjectQuery(<TestDummy 280 />).
at oracle.tip.adapter.db.exceptions.DBResourceException.createEISException(DBResourceException.java:469)
at oracle.tip.adapter.db.exceptions.DBResourceException.outboundWriteException(DBResourceException.java:510)
at oracle.tip.adapter.db.DBInteraction.executeOutboundWrite(DBInteraction.java:963)
at oracle.tip.adapter.db.DBInteraction.execute(DBInteraction.java:225)
at oracle.tip.adapter.fw.wsif.jca.WSIFOperation_JCA.executeRequestResponseOperation(WSIFOperation_JCA.java:485)
at com.collaxa.cube.ws.WSIFInvocationHandler.invoke(WSIFInvocationHandler.java:435)
at com.collaxa.cube.ws.WSInvocationManager.invoke2(WSInvocationManager.java:443)
at com.collaxa.cube.ws.WSInvocationManager.invoke(WSInvocationManager.java:251)
at com.collaxa.cube.engine.ext.wmp.BPELInvokeWMP.__invoke(BPELInvokeWMP.java:727)
I decided to test this on my local SOA Suite, instead of deploying to the development server, and again to my surprise, the exception was caught and handled as expected, with no errors thrown. I then realized that I hadn’t set up the datasource, connection pool, and DbAdapter connection factory in Enterprise Manager for the database being used. I configured these appropriately, and once again the above error happened, this time on my local SOA Suite. I removed the connection from the DbAdapter connection factory, and the exception was once again caught and handled appropriately.
Since our database passwords have to be changed periodically, we are required to configure the datasource etc on the server so password management can be done in one place. That being the case, I’m hoping someone can provide some ideas to help resolve this issue. I tried changing a few of the database settings in Enterprise Manager (using dataSourceName instead of xADataSourceName, setting usesBatchWriting to false instead of true) but none of these changes worked.
ThanksYou should look into Bridge [GOF:151] and Memento [GOF:273].
Bridge allows you to decouple your mechanism from the implementation memento on how to propergate the decoupled exception information. -
It takes long time to invoke the Exception handler code
In our setup there is firewall between the Appserver that is using toplink and the database.The firewall terminates idle connection on any port if the connection is idle for 1 hr.So i have implemented an exception handler to reconnect when the connection is broken.The code works fine but It takes 15 mins for the exception handler code to be invoked.
The database is Oracle and the driver is thin driver,OS is solaris.No external connection pool
I had registered the exceptionhandler to the serversession,should i register it with each ClientSession?yes ,15 mins is the time taken before the server session's exception handler code is invoked.
The following is the exception handler code on the sever session.Any thing wrong?
server.setExceptionHandler(new ExceptionHandler()
public Object handleException(RuntimeException ex)
{//This method is executed only after 15 min ,if the connection is broken
String mess=ex.getMessage();
System.out.println("In handler excep mess is "+mess);
if ((ex instanceof DatabaseException) && (mess.equals("connection reset by peer.")||(mess.indexOf("IOException :Broken pipe")!=-1)))
DatabaseException dbex = (DatabaseException) ex;
dbex.getAccessor().reestablishConnection (dbex.getSession());
return dbex.getSession().executeQuery(dbex.getQuery());
return null;
What could be wrong ?
I tried Oracle's connection cache Impl created a connection pool using the same thin driver and on the same env.SQLException is thrown immediately on using the broken connection.so I feel the driver is not causing any problem.
Is there any way in toplink to keep the connections active?or Is there any way to poll all connections in the connection pool and check If they are connected instead of waiting until the exception gets thrown and handle it? -
Exception Handling related problem
Can anybody tell me why it is not giving ArithmeticException.
package pckg1;
* @author anil_saini
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
import java.io.FileNotFoundException;
public class Average7 {
public static void main(String[] args) throws InterruptedException,FileNotFoundException {
try { // (1) System.out.println(printAverage(100, 0)); // (2)
} catch (ArithmeticException ae) { // (3)
Thread.sleep(1000);
ae.printStackTrace(); // (4)
System.out.println("Exception handled in " + // (5)
"main().");
finally {
System.out.println("Finally in main()."); // (6)
System.out.println("Exit main()."); // (7)
public static int printAverage(int totalSum, int totalNumber) {
int average=0;
try { // (8)
average = computeAverage(totalSum, totalNumber); // (9)
System.out.println("Average = " + // (10)
totalSum + " / " + totalNumber + " = " + average);
return average;
} catch (IllegalArgumentException iae) { // (11)
iae.printStackTrace(); // (12)
System.out.println("Exception handled in " + // (13)
"printAverage().");
} finally {
System.out.println("Finally in printAverage()."); // (14)
return average;
} // (15)
public static int computeAverage(int sum, int number) {
System.out.println("Computing average.");
if (number == 0) // (16)
throw new ArithmeticException("Integer division by 0");// (17)
return sum/number; // (18)
Output
=======================
Computing average.
Finally in printAverage().
0
Finally in main().
Exit main().Because return statements in finally blocks are evil!
int average = 0;
try
{ // (8)
average = computeAverage(totalSum, totalNumber); // (9)
System.out.println("Average = " + // (10)
totalSum + " / " + totalNumber + " = " + average);
return average;
catch (IllegalArgumentException iae)
{ // (11)
iae.printStackTrace(); // (12)
System.out.println("Exception handled in " + // (13)
"printAverage().");
throw new IllegalArgumentException();
finally
System.out.println("Finally in printAverage()."); // (14)
return average; // (15)
}You get an exception at (9), but finally is guaranteed to be executed, so the JVM executes it. Now you return in your finally block (15), and the JVM is left with the choice of executing your return statement or propagating the exception. Since, as said, finally is guaranteed to be executed, it returns and swallows the exception.
That's why IMHO return statements in finally blocks should not be allowed.
(Some compilers issue warnings)
If you move your return statement out of the finally block, it will work as you'd expect it. -
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 -
Problem in Exception Handling...URGENT
hi, actually i am trying to make a program using Lucene Api and Using NGramSpeller...
the information about NGramSpeller is here
http://www.marine-geo.org/services/oai/docs/javadoc/org/apache/lucene/spell/NGramSpeller.html#suggestUsingNGrams(org.apache.lucene.search.Searcher,%20java.lang.String,%20int,%20int,%20int,%20float,%20float,%20float,%20int,%20java.util.List,%20boolean)
and here is my code..
package org.apache.lucene.spell;
import java.io.IOException;
import java.io.File;
import java.io.*;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.spell.NGramSpeller;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.analysis.*;
import org.apache.lucene.index.*;
import org.apache.lucene.store.*;
import org.apache.lucene.document.*;
import org.apache.lucene.search.*;
import org.apache.lucene.search.BooleanClause.Occur;
import java.lang.*;
public class spell1 {
public static void main(String args[]) throws IOException {
try{
System.out.println("enter the keyword");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));//USER INPUT KEYWORDS
String the_query = in.readLine();
//String spellIndex = "C:/opt/lucene/didyoumean/indexes/spell";
String spellIndex1 = "C:/Documents and Settings/sumit-i/Desktop/ngramspell/ngramspell";
Searcher spellIndex = new IndexSearcher(spellIndex1);
NGramSpeller spellChecker = new NGramSpeller();
float a=2.0f, b=1.0f, c=0.0f;
try{
String[] similarWords = spellChecker.suggestUsingNGrams(spellIndex, "jva", 3, 3, 10, a, b, c, 0, null, true);
System.out.println("DO YOU MEAN.........");
for(int i=0;i<similarWords.length;i++)
System.out.println(similarWords);
catch (IOException e) {
throw e;
in.close();
catch (IOException ioe)
ioe.printStackTrace();
the error i am getting is due to some exception handling problem, which is as follows:package org.apache.lucene.spell;
import java.io.IOException;
import java.io.File;
import java.io.*;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.spell.NGramSpeller;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.analysis.*;
import org.apache.lucene.index.*;
import org.apache.lucene.store.*;
import org.apache.lucene.document.*;
import org.apache.lucene.search.*;
import org.apache.lucene.search.BooleanClause.Occur;
import java.lang.*;
public class spell1 {
public static void main(String args[]) throws IOException {
try{
System.out.println("enter the keyword");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));//USER INPUT KEYWORDS
String the_query = in.readLine();
//String spellIndex = "C:/opt/lucene/didyoumean/indexes/spell";
String spellIndex1 = "C:/Documents and Settings/sumit-i/Desktop/ngramspell/ngramspell";
Searcher spellIndex = new IndexSearcher(spellIndex1);
NGramSpeller spellChecker = new NGramSpeller();
float a=2.0f, b=1.0f, c=0.0f;
try{
String[] similarWords = spellChecker.suggestUsingNGrams(spellIndex, "jva", 3, 3, 10, a, b, c, 0, null, true);
System.out.println("DO YOU MEAN.........");
for(int i=0;i<similarWords.length;i++)
System.out.println(similarWords[i]);
catch (IOException e) {
throw e;
in.close();
catch (IOException ioe)
ioe.printStackTrace();
any idea....plzzzwhat about this??
try{
String[] similarWords = spellChecker.suggestUsingNGrams(spellIndex, "jva", 3, 3, 10, a, b, c, 0, null, true);
System.out.println("DO YOU MEAN.........");
for(int i=0;i<similarWords.length;i++)
System.out.println(similarWords);
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("exception: " + e.getMessage());
e.printStackTrace(); -
Cache Synchronization Exception Handling
I am setting up cache synchronization on WebLogic using JMS. I am looking into writing an exception handler to handle cache synchronization exceptions. The following statement in the documentation caught my attention:
As mentioned above, the TopLink cache does not begin the merge or update process until the database transaction has already been committed. This is quite beneficial in that it avoids letting uncommitted data into the shared cache, but should be recognized where transactional synchronization is considered. In cases where a merge may have failed there is no way to roll back the changes made to the database (although it is questionable whether this would be a good idea in any case). As a consequence, failures during remote merging can leave the cache in an inconsistent state. This makes it important to handle any errors that occur by performing cache normalization actions, such as resetting the cache, or even the server.
Suppose we have two app server instances, A and B. Instance A commits a change and sends the update notification to instance B. The merge fails on instance B with an optimistic lock exception.
- I assume that a CacheSynchronizationException will be thrown. Will it be thrown on instance A, B, or both?
- At this point which cache is inconsistent; A, B, or both?
- The documentation suggests resetting the cache, but this seems a rather severe way of dealing with the problem. Is it feasible / effective to just refresh the objects in the change set of the CacheSynchronizationException?
This is a simple exception handler. On receiving a CacheSynchronizationException it resets the cache and re-throws the exception.
class ToplinkExceptionHandler implements ExceptionHandler{
public Object handleException(RuntimeException exception) throws DatabaseException{
if(exception instanceof CacheSynchronizationException){){
myServerSession.initializeAllIdentityMaps();
throw exception;
}else{
throw exception;
- Is this approach effective?
- Once the cache is reset should the exception be re-thrown or should I consider it handled and swallow it? If I do swallow it what should the method return?
Any advice would be appreciated.I had to fix a few errors (in our code) before getting it working. Since I have multiple sessions, I had to specify different multicast ports (actually I used a different multicast address itself) for each of the sessions. I was not setting the announcement delay on one of the sesssions and that was why it was announcing immediately upon coming up. Also I had to explicitly set asynchronous to false because it is true by default.
BTW, we are not using CMP (entity beans) rather Java Objects. Our deployment has two Apache/Tomcat machines and two WebLogic machines. The WebLogic servers are in a round-robin cluster. The cache synchronization seems to be working fine for this configuration.
Thanks.
Anand R -
Purpose of throws clause in exception handling
hi all,
I have written a sample code for exception handling...please refer below....
class a
void fun() throws ArithmeticException
int i=0;
i=10/0;
class exec
public static void main(String a[])
a a1=new a();
try{a1.fun();}
catch(ArithmeticException e){System.out.println("hi");}
}I read the article...and came out with these points...
1..If method is throwing an unchecked exception (as in this case) then there is no need for throws clause, if you are not catching it then and there only.....
2...if a method is throwing a checked exception then either you need to catch it then and there only or you must specify a throws clause for the same in function definition......*And the purpose of not catching it then and there only is*
"For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package. In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it."
M I RIGHT?? -
C call-out and exception handling on HP_UX
Does anyone have experiencing calling out to C++ code which uses exception
handling on HP_UX? I'm having trouble getting this to work - details
below.
I'm trying to call out of Forte to some C++ code. The exposed functions
have been specified extern "C". This C++ code makes calls to the Lotus
Notes' C++ API. This API uses exception handling, as does our C++ code.
This all works great on Window NT. It's pretty cool, in fact.
It's not so cool on HP_UX. We're running 10.20, Forte 3.0.E. Apparently,
under HP_UX you have to compile and link using the +eh option in order to
use exception handling. So I did this. My test driver (which calls out to
my user object module) works fine.
So I fired up fcompile, passing in the +eh arguments, and the location of
one of Lotus Notes' shared libraries:
fcompile -cflags eh -lflags "eh /opt/lotus/notes/latest/hppa/libnotes.sl"
It works, giving me no errors.
Then I try to call the functions from inside Forte. It gives me the "Not
enough space loading library blah-blah-blah" error message. In my
experience, this message is misleading, and there's actually something else
going on. So I looked at the log file for the node manager. I saw these
messages:
/usr/lib/dld.sl: Unresolved symbol: __eh_Cqqsh_DynScope (data) from
/tools/forte/EdgeNotes/userapp/conplus_/cl0/lnapifor.sl
/usr/lib/dld.sl: Unresolved symbol: __eh_dt_count (data) from
/tools/forte/EdgeNotes/userapp/conplus_/cl0/lnapifor.sl
/usr/lib/dld.sl: Unresolved symbol: __eh_reset_dt_count (data) from
/tools/forte/EdgeNotes/userapp/conplus_/cl0/lnapifor.sl
/usr/lib/dld.sl: Unresolved symbol: __eh_Cqqlo_Object (data) from
/tools/forte/EdgeNotes/userapp/conplus_/cl0/lnapifor.sl
/usr/lib/dld.sl: Unresolved symbol: dealloc_object__18__eh_thrown_objectFi
(code) from /tools/forte/EdgeNotes/userapp/conplus_/cl0/lnapifor.sl
I don't know what this all means. In an attempt to replicate the situation
as closely as possible, I tried linking in the shared library (created by
Forte) to my driver program, and ran my driver program. It worked,
although it gave me the following warnings:
__link_incompatibility: Warning: Shared library
/tools/forte/EdgeNotes/install/lib/libqqfo.sl was not compiled with +eh.
__link_incompatibility: Warning: Shared library
/tools/forte/EdgeNotes/install/lib/libqqrpgs.sl was not compiled with +eh.
__link_incompatibility: Warning: Shared library
/tools/forte/EdgeNotes/install/lib/libqqsm.sl was not compiled with +eh.
__link_incompatibility: Warning: Shared library
/tools/forte/EdgeNotes/install/lib/libqqdo.sl was not compiled with +eh.
__link_incompatibility: Warning: Shared library
/tools/forte/EdgeNotes/install/lib/libqqcm.sl was not compiled with +eh.
__link_incompatibility: Warning: Shared library
/tools/forte/EdgeNotes/install/lib/libqqknpthrd.sl was not compiled with
+eh.
Hmmm .... After further investigation, I found that the
"__eh_Cqqsh_DynScope", "__eh_dt_count", and
"dealloc_object__18__eh_thrown_objectFi" symbols are referenced from my
user object module, and not from any of Forte's libraries (via the nm
command).
My guess is that there's an incompatibility between the forte run-time, and
my code, and I'm further guessing that this incompatibility is related to
the fact that my code is using exception handing.
I'm in contact with Forte Tech Support, but I wanted to see if anyone on
this list has ever run across this.
Thanks,
Dan
[email protected]I did not know that the 9.2 Oracle ODBC driver was not certified for Oracle 7
In fact, when I read the help in the Oracle Net Manager that I installed from the same package (OraWin9204.exe), I can see that there is a normal conncection possible between the packed software and Oracle 7. Downward compatibility is something we should expect from astate-of-the-art RDBMS like Oracle.
I do not have the Oracle 7 ODBC driver installed, I was since two years using the Oracle 8 ODBC driver wich worked fine with both Oracle 7 and 8 but due to upgrading of one of our production databases to Oracle 9 I had to install the Oracle 9 software.
As I stated in my original mail, when testing the Oracle 9 driver in the Data source (ODBC) off my WinXP, it gives a perfect result while connectiing to the System DSN I configured for the Oracle 7 database.
But when opening Access2003 and linking tables, the ODBC call always fails
BR,
Theo -
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 -
Issue with exception Handling in GG
Hi,
I have bi-directional DML replication setup. I have written a code in replication parameter for handling the exception , Exception handling is working fine my replicate process is not getting ABENDED but Issue is I am not geeting any rows in EXCEPTION table.I had gone through replicat report, there I had seen GG is trying to inser duplicate records in EXCEPTION TABLE and it is failing because of that .
**Command for create Exception Table is-**
create table ggs_admin.exceptions (
rep_name varchar2(8) ,
table_name varchar2(61) ,
errno number ,
dberrmsg varchar2(4000) ,
optype varchar2(20) ,
errtype varchar2(20) ,
logrba number ,
logposition number ,
committimestamp timestamp,
CONSTRAINT pk_exceptions PRIMARY KEY (logrba, logposition, committimestamp)
USING INDEX
TABLESPACE INDX1
TABLESPACE dbdat1
My replication parameter is-
GGSCI (db) 1> view params rep2
-- Replicator parameter file to apply changes
REPLICAT rep2
ASSUMETARGETDEFS
USERID ggs_admin, PASSWORD ggs_admin
DISCARDFILE /u01/app/oracle/product/gg/dirdat/rep2_discard.dsc, PURGE
-- Start of the macro
MACRO #exception_handler
BEGIN
, TARGET ggs_admin.exceptions
, COLMAP ( rep_name = "REP2"
, table_name = @GETENV ("GGHEADER", "TABLENAME")
, errno = @GETENV ("LASTERR", "DBERRNUM")
, dberrmsg = @GETENV ("LASTERR", "DBERRMSG")
, optype = @GETENV ("LASTERR", "OPTYPE")
, errtype = @GETENV ("LASTERR", "ERRTYPE")
, logrba = @GETENV ("GGHEADER", "LOGRBA")
, logposition = @GETENV ("GGHEADER", "LOGPOSITION")
, committimestamp = @GETENV ("GGHEADER", "COMMITTIMESTAMP"))
, INSERTALLRECORDS
, EXCEPTIONSONLY;
END;
-- End of the macro
REPERROR (DEFAULT, EXCEPTION)
--REPERROR (-1, EXCEPTION)
--REPERROR (-1403, EXCEPTION)
MAP scr.order_items, TARGET scr.order_items;
MAP scr.order_items #exception_handler();
GGSCI (db) 2>view params rep2
MAP resolved (entry scr.order_items):
MAP "scr"."order_items" TARGET ggs_admin.exceptions , COLMAP ( rep_name = "REP2" , table_name = @GETENV ("GGHEADER", "TABLENAME") , errno = @GETENV ("LASTERR", "DB
ERRNUM") , dberrmsg = @GETENV ("LASTERR", "DBERRMSG") , optype = @GETENV ("LASTERR", "OPTYPE") , errtype = @GETENV ("LASTERR", "ERRTYPE") , logrba = @GETENV ("GGHEADER"
, "LOGRBA") , logposition = @GETENV ("GGHEADER", "LOGPOSITION") , committimestamp = @GETENV ("GGHEADER", "COMMITTIMESTAMP")) , INSERTALLRECORDS , EXCEPTIONSONLY;;
Using the following key columns for target table GGS_ADMIN.EXCEPTIONS: LOGRBA, LOGPOSITION, COMMITTIMESTAMP.
2012-08-30 09:09:00 WARNING OGG-01154 SQL error 1403 mapping scr.order_items to scr.order_items OCI Error ORA-01403: no data found, SQL <DELETE FROM "scr"."order_items" WHERE "SUBSCRIBER_ID" = :b0>.
2012-08-30 09:09:00 WARNING OGG-00869 OCI Error ORA-00001: unique constraint (GGS_ADMIN.PK_EXCEPTIONS) violated (status = 1). INSERT INTO "GGS_ADMIN"."EXCEPTIONS" ("R
EP_NAME","TABLE_NAME","ERRNO","DBERRMSG","OPTYPE","ERRTYPE","LOGRBA","LOGPOSITION","COMMITTIMESTAMP") VALUES (:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8).
2012-08-30 09:09:00 WARNING OGG-01004 Aborted grouped transaction on 'GGS_ADMIN.EXCEPTIONS', Database error 1 (OCI Error ORA-00001: unique constraint (GGS_ADMIN.PK_EX
CEPTIONS) violated (status = 1). INSERT INTO "GGS_ADMIN"."EXCEPTIONS" ("REP_NAME","TABLE_NAME","ERRNO","DBERRMSG","OPTYPE","ERRTYPE","LOGRBA","LOGPOSITION","COMMITTIMES
TAMP") VALUES (:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8)).
2012-08-30 09:09:00 WARNING OGG-01003 Repositioning to rba 92383 in seqno 8.
2012-08-30 09:09:00 WARNING OGG-01154 SQL error 1403 mapping scr.order_items to scr.order_items OCI Error ORA-01403: no data found, SQL <DELETE FROM "scr"."order_items" WHERE "SUBSCRIBER_ID" = :b0>.
2012-08-30 09:09:00 WARNING OGG-01154 SQL error 1 mapping scr.order_items to GGS_ADMIN.EXCEPTIONS OCI Error ORA-00001: unique constraint (GGS_ADMIN.PK_EXCEPTIONS)
violated (status = 1). INSERT INTO "GGS_ADMIN"."EXCEPTIONS" ("REP_NAME","TABLE_NAME","ERRNO","DBERRMSG","OPTYPE","ERRTYPE","LOGRBA","LOGPOSITION","COMMITTIMESTAMP") VAL
UES (:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8).
2012-08-30 09:09:00 WARNING OGG-01003 Repositioning to rba 92383 in seqno 8.
When I am running command
select * from exceptions;
no row selected.
Please help. Why duplicat rows trying to insert in Exception table.Remove (disable) the constraint on the exceptions table and see if inserts will take place. Do you really need that primary key?
-
Exception Handling-rite way??
Hi Friends,
This Exception handling is really causing some problems for me.I run a query,return the resultset,cook the data from my other java class and display it thru my jsp and the last statement from my jsp is to call the close method(commented out).The problem is if some unknown Exception arises the close() method is not being called,causing open connections which later on are
creating some disasters.I tried to implement it now using the finally method,so that it always gets closed,but hte problem is when i call the ReturnResultSet() method and try to cook the data,it says "ResultSet Closed".Please tell me which is the right way to implement this:
public ResultSet ReturnResultSet(String Query) throws Exception
try{
if (datasource != null) {
connection = datasource.getConnection();
if (connection != null) {
statement = connection.createStatement( );
resultset = statement.executeQuery(Query);
return resultset;
} catch (SQLException sqle)
sqle.printStackTrace();
return null;
finally {
try {
if (resultset != null) resultset.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
catch (SQLException sqle) {
sqle.printStackTrace();
public void close()
try { resultset.close(); } catch (Exception ex) {}
try { statement.close(); } catch (Exception ex) {}
try { connection.close(); } catch (Exception ex) {}
*/Any help would be appreciated and some duke dollars would be awarded too.ThanksOk I think i got your point and i should award you
the duke dollars too,but one last thing to ask.I call
the close() method after all my processing is over,I
just
wanna know should I have the connection.close() thing
inside it,becuase dont that contradicts the whole
connection pool thing,as i am closing a connection
and it has to open a new connection for every
request.Or should i just have resultset.close() and
statement.close() in it.
Thanks for all your helpAre you talking about a standard J2EE container-provided connection pool? If so, then yes, you still need to 'close' the connection. That doesn't actually close it, it just tells the pool it is available to be used again the next time someone asks it for a connection. Hopefully you're not writing your own home-grown "connection pool".
Maybe you are looking for
-
Safari and all other web browsers freeze with flash
This is a recent problem. For some reason in the past 2 days safari has completely stopped working for me on normal websites with flash. For example whenever I go to espn.com safari will load about 95% of the page and then it freezes up. It worked pe
-
Trying to download itunes and getting error 7 - windows error 193. What does this mean?
-
Hi, can any one help me on how to read pdf files in java using itext. I have written some piece of code but it is of no use. It is giving some garbage. import java.io.*; import java.util.*; import java.lang.*; import com.lowagie.text.pdf.PdfReader; p
-
"Permanently" Crop Clips?
I would like to "permanently" crop and/or split video clips while editing raw video within iMovie. I have been editing sports video (e.g. soccer game action) for highlight movies where I typically need only a small fraction of the video for the finis
-
NCS 1.1.1.24 migration to PI 1.2.1.012
I have an open TAC case on this also....but it's taking longer than usual for them to get pertinent info back to me so figured I'd try here. I'm in the process of migrating from WCS to Prime Infrastructure 1.2 I've already sucessfully completed the