Exception handling in procedures/functions
I want to know if an exceptions can be handled inside a while loop in Oracle procedures/functions?
thanks in advanced,
Abhijit,
Darn while writting an answer other people already did as well (coooool). I guess I'll still post my reply :).
In my example, I cause the error by doing 0/0 (can't divide by zero) but the loop still continues. You can copy/paste this in sqlplus and it should give you the same output as me.
--[START]
create or replace procedure sp_test as
li_loop number := -1;
li_temp number;
begin
while li_loop < 10 loop
li_loop := li_loop + 1;
begin
select li_loop/li_loop into li_temp from dual;
EXCEPTION WHEN OTHERS THEN
dbms_output.put_line ('ERROR IS : ' || sqlerrm);
end;
dbms_output.put_line ('loop value is [' ||to_char(li_loop) || ']');
end loop;
end;
set serveroutput on;
execute sp_test;
--[END]
ERROR IS : ORA-01476: divisor is equal to zero
loop value is [0]
loop value is [1]
loop value is [2]
loop value is [3]
loop value is [4]
loop value is [5]
loop value is [6]
loop value is [7]
loop value is [8]
loop value is [9]
loop value is [10]
PL/SQL procedure successfully completed.
SQL>
Have a happy coding day,
Tyler
Similar Messages
-
Exception Handling for a function module
There is a function module the program in which exceptions are handled. When the program is ran as a background job and when there is a exception arises does the background job fails or the exception gets handled ??? Pls help me out.....
it raises an exception you can catch it.
cx_root is the root class for exceptions.
DATA: ex TYPE REF TO CX_ROOT.
TRY.
call fm.
CATCH cx_root INTO ex.
ENDTRY.
message = cx_root->get_text( ).
this way your program will not stop..
regards,
Aparna -
Need of exception handler in calling function, isn't that weird???
Hi,
I have written a function as follows
public String fetchName(String query) throws Exception
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.next();
return (rs.getString(1));
I've handled the for exceptions here using "throws Exception". Inspite of that when i call it from other function and in that funtion no exception need to be handled, compiler gives errror.
Following is the calling funtion
public String checksubAction(String action)
String retValue=" ";
String query="";
query = "select Title from dbo.Folder where Folder_Id="+folderId;
retValue = dataBaseObj.fetchName(query);
but when i write it in try-catch block, no errror is given.
Why is it that inspite of handling exception(s) in the called function, we need to handle them in calling functions.No you have not handled the exception. Your code say "fetchName" does NOT handle exceptions of type "Exception", the calling method should be aware of this, and handle that type of exception.
The Java Tutorial: Essential Java Classes: Handling Errors Using Exceptions
(Please when declaring a method can throw exceptions, be specific, i.e. throw SQLException in this case) -
Parameter index move while executing PL/SQL stored procedure/function
Hello, community.
Have a question for you. It looked like very easy to write some small JDBC-wrapper to handle stored procedure/functions call for Oracle.
Here is the code snippet of it:
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import javax.sql.DataSource;
import oracle.jdbc.driver.OracleTypes;
import org.apache.log4j.Logger;
public class SmallHelper {
public static final int CALL_TYPE__PROCEDURE = 1;
public static final int CALL_TYPE__FUNCTION = 2;
public static final int PARAMETER__IN = 1;
public static final int PARAMETER__OUT = 2;
private static final Logger log = Logger.getLogger(SmallHelper.class);
private Connection con = null;
private CallableStatement statement = null;
private String name;
private int type;
private int resultType;
private HashMap arguments = new HashMap();
* Creates connection using data source as parameter.
* @param ds - data source
* @throws EhlApplicationException
public SmallHelper(DataSource ds) throws Exception {
try {
con = ds.getConnection();
catch (SQLException e) {
ExceptionHelper.process(e);
public void registerProcedure(String name) {
this.name = name;
this.type = CALL_TYPE__PROCEDURE;
public void registerFunction(String name, int resultType) {
this.name = name;
this.resultType = resultType;
this.type = CALL_TYPE__FUNCTION;
* NB! When You're dealing with stored function index should start with number 2!
public void registerArgument(int index, Object value, int type, int inOutType) {
arguments.put(new Long(index), new CallableStatementArgument(value, type, inOutType));
private String getSQL() {
StringBuffer str = new StringBuffer("{ call ");
if ( type == CALL_TYPE__FUNCTION )
str.append(" ? := ");
str.append(name).append("( ");
for ( Iterator i = arguments.values().iterator(); i.hasNext(); ) {
i.next();
str.append("?");
if ( i.hasNext() )
str.append(", ");
str.append(") }");
return str.toString();
public void execute() throws SQLException{
String query = getSQL();
statement = con.prepareCall(query);
if ( type == CALL_TYPE__FUNCTION )
statement.registerOutParameter(1, resultType);
for ( Iterator i = arguments.keySet().iterator(); i.hasNext(); ) {
Long index = (Long) i.next();
CallableStatementArgument argument = (CallableStatementArgument) arguments.get(index);
int type = argument.getType();
if ( argument.getInOutType() == PARAMETER__OUT )
statement.registerOutParameter(index.intValue(), type);
else if ( type != OracleTypes.CURSOR )
statement.setObject(index.intValue(), argument.getValue(), type);
log.info("Executing SQL: "+query);
statement.execute();
public CallableStatement getStatement() {
return statement;
public void close() throws EhlApplicationException {
try {
if (statement != null)
statement.close();
if (con != null)
con.close();
catch (SQLException e) {
EhlSqlExceptionHelper.process(e);
private class CallableStatementArgument implements Serializable{
private Object value;
private int type;
private int inOutType;
public CallableStatementArgument(Object value, int type, int inOutType) {
this.value = value;
this.type = type;
this.inOutType = inOutType;
public int getType() {
return type;
public Object getValue() {
return value;
public int getInOutType() {
return inOutType;
}It was really done in 10-15 mins, so don't be very angry at code quality :)
Here is the problem.:
helper.registerProcedure("pkg_diagnosis.search_diagnosis");
helper.registerArgument(1, null, OracleTypes.CURSOR, EhlJdbcCallableStatementHelper.PARAMETER__OUT);
helper.registerArgument(2, pattern, OracleTypes.VARCHAR, EhlJdbcCallableStatementHelper.PARAMETER__IN);
helper.registerArgument(3, lang, OracleTypes.VARCHAR, EhlJdbcCallableStatementHelper.PARAMETER__IN);
helper.registerArgument(4, EhlSqlUtil.convertSetToString(langs, ","), OracleTypes.VARCHAR, EhlJdbcCallableStatementHelper.PARAMETER__IN);
helper.registerArgument(5, EhlSqlUtil.convertSetToString(diagnosisClass, ","), OracleTypes.VARCHAR, EhlJdbcCallableStatementHelper.PARAMETER__IN);
helper.registerArgument(6, parentId, OracleTypes.NUMBER, EhlJdbcCallableStatementHelper.PARAMETER__IN);
helper.execute();
ResultSet rs = ((OracleCallableStatement) helper.getStatement()).getCursor(1);
procedure definition:
procedure search_diagnosis (l_res OUT dyna_cur,
in_search_string IN VARCHAR2,
in_search_lang IN VARCHAR2,
in_lang_list IN VARCHAR2,
in_diag_class_list IN VARCHAR2,
in_parent_id IN NUMBER) Procedure call has inner check that fail because of som strange reason:
in_search_string has 2 as index, that is correct. but procedure recieves is as number 3 in parameter list (what is in_search_lang). Other parameters are moved to. It seems like a cursor takes 2 places in definition. It's clear that if I put in_search_string as 1 parameter and cursor as 0 I'll get invalid parametr bindong(s) exception. So... any ideas why 2nd parameter is actually 3rd?
Thanks beforehand.hmm...moreover:
if we change procedure to function and call it in a simple way:
CallableStatement stmnt = helper.getConnection().prepareCall("begin ? := pkg_diagnosis.search_diagnosis(?,?,?,?,?); end;");
stmnt.registerOutParameter(1, OracleTypes.CURSOR);
stmnt.setString(2, pattern);
stmnt.setString(3, lang);
stmnt.setString(4, langs);
stmnt.setString(5, diagnosisClass);
stmnt.setObject(6, parentId, OracleTypes.NUMBER);
stmnt.execute();
ResultSet rs = (ResultSet) stmnt.getObject(1);the exception is:
[BEA][Oracle JDBC Driver][Oracle]ORA-06550: line 1, column 14:
PLS-00382: expression is of wrong type
ORA-06550: line 1, column 7:
PL/SQL: Statement ignoredif we return some string or number - it works. but when we want cursor back - it fails.
cursor is defined like ordinary dynamic cursor:
TYPE dyna_cur IS REF CURSOR; -
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
***/ -
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 -
Get Attribute values from a page and procedure exception handling?
Hi All,
I have created new page with two input attributes not based on any VO. This page is created to capture two values and pass these to an AM method upon pressing OK button. The method in AM will call a procedure with two in parameter expecting the two values captured from the above said page.
I have two questions, first one how to capture the values entered by the page in the controller class and advises me how to handle exceptions when my procedure fails.
I can not use something like this since this page is not based on a VO
String fromName = (String)vo.getCurrentRow().getAttribute("FromName");
Do I have to create a dummy VO like select '' name1, '' name2 from dual?
Thanks for the help.Hi,
Actually you can capture the parameters on the page like this way
String test = (String)pageContext.getParameter("id of the text input bean");
Now in procedure you can take an out parameter which stores the error messages on exception
and return that out parameter in java.
and then you can throw exception on page using OAException class.
Thanks
Gaurav Sharma -
Exception handling in Custom Login procedure
Hi,
I have a custom login procedure. Now instead of handling the possible exceptions in a custom way too, I want to use the syntax of the exception handling API (probably the one in the PDK) the default login procedure uses. Can someone point me to the values the default login procedure uses?
Thanks, TonyTony,
The default login page (the source of which is now unwrapped in 3.0.0), uses the following snippet of code to report the errors:
if p_error then
wwerr_api_error_ui.show_inline_html;
end if;The errors are stacked when the ls_login procedure is executed, and the next time the login page is called up, it just displays the stacked errors. -
Resume procedure execution after Exception Handler
Hi -- Can anyone tell me how to resume execution of my procedure if and when I fall into the Exception Handler?
I'm in a for/loop and i want to move to the next record after falling into the exception handler.
Thanks,
~ChristineIt's just a scoping issue...
BEGIN
FOR r IN ( SELECT ... FROM whatever ) LOOP
BEGIN
-- do stuff
EXCEPTION
WHEN others THEN
log_error(SQLERRM);
END;
END LOOP;
END;
/If you're using BULK processing you may want to check out %BULK_EXCEPTIONS.
Cheers, APC -
Handle invalid_number exception for a procedure with numeric in paramete
I have a procedure that takes an input parameter as number(numeric datatype) how can i handle an invalid_number exception (-01722) to display a message when a user tries entering non-numeric input
the procedure is shown below..
create or replace procedure orders(custid_in IN number) is
cursor order_cur is
select order_id, order_date, total
from product_order
where customer_id = to_number(custid_in);
order_row order_cur%rowtype; -- declare cursor variable
err_msg varchar2(512);
BEGIN
dbms_output.put_line('Order Details for customer with customer id '||custid_in|| ' is shown below: ');
dbms_output.put_line((chr(9)));
open order_cur;
LOOP
fetch order_cur into order_row;
exit when order_cur%notfound ;
dbms_output.put_line('Order ID: '||order_row.order_id);
dbms_output.put_line('Order Date: '||order_row.order_date);
dbms_output.put_line('Total: '||order_row.total);
dbms_output.put_line((chr(9)));
END LOOP;
close order_cur;
EXCEPTION
when invalid_number then
dbms_output.put_line('Customer ID not correct. Try again! ');
dbms_output.put_line((chr(9)));
WHEN others THEN
err_msg := sqlerrm;
dbms_output.put_line('The following error occured: ');
dbms_output.put_line(err_msg);
END;My first recommendation is to remove the type conversion from your cursor:
cursor order_cur is
select order_id, order_date, total
from product_order
where customer_id = to_number(custid_in);making itcursor order_cur is
select order_id, order_date, total
from product_order
where customer_id = custid_in;because you are already passing it into your stored procedure as parameter of type number.
Then if you really want to check for the invalid number exception you will probably need to do it from where ever you are calling the procedure from since it's going to occur at the time it's called rather than once you are inside the procedure.
And finally, remove your final exception handler (the WHEN OTHERS exception) it serves no useful purpose and is in point of fact detrimental to your code in that it may improperly handle unexpected errors and allow processing to continue when it should not. -
Handle exception and finish procedure
Hi everybody,
I have a Store Procedure and I have some exceptions handling but when my procedure catches an exception, it finish abruptly. Is there a way to catch the exceptions and let the procedure continue with the next part until the very end of the procedure? (if there are many exceptions handle them but never finish the procedure abruptly)
Thanks for any advice you can give,
FedericoThis is the forum for SQL Developer (Not for general SQL/PLSQL questions), your question would be better asked in the SQL and PL/SQL forum.
You may be catching the exceptions, but you are not handling them if your procedure terminates.
begin
-- some query
exception
-- handle no_data_found
when no_data_found then
nodata:=true;
-- don't handle anything else
when others then
raise;
end;
-- more code -
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 -
Status report from Procedure/functions
All,
I have procedures /functions in my database. I need to return a status value back to the call procedures/functions to report the sub_procedure/function executed successfully.
What is the status value if a procedure/function executed successfully? And what is the value for un_successful execution? Where I can get it from?
Thanks a lot!This is really a design choice that you have to make in your application. PL/SQL stored procedures / functions do not return any implicit status codes on there own. In your PL/SQL code, you can check the SQLCODE built-in function for the status of the last SQL statement executed, but this is hardly the same thing (and really designed for use in exception handlers).
You may choose to design you applications such that every call must return a status value. In this case, the values used to represent success or failure are up to you (I might suggest 0 for success and the error code - which will be non-zero - for failure). You can either use functions which always return a number (probably not a good idea to place this limitation on your application); you might design all stored procedures to return an output parameter which indicates success or failure.
But, in general, your client code should be designed to correctly handle all Oracle exceptions - if no exception is raised, then success, else failure. And your PL/SQL should avoid bad practices like exception handlers which trap WHEN OTHERS and don't re-raise the exception. -
Exception handling raised in named subprograms
Hi,
I would like to call three procedures from a when button pressed trigger and deal with them individually.
I tried naming the exception in the procedure, not to handle it there, and get it to propagate in the calling trigger.
Here is the code for the When-Button-Pressed Trigger:
declare
too_much exception;
begin
p_valider_total_ht;
:b_utils.f_nom := 'Everythingsfine' ;
go_item( 'B_UTILS.F_NOM' );
exception
when others then
lib_alert(' Exc en pb valider ' || to_char(sqlcode) || 'xxx' || sqlerrm );
end;
Here is the code for the procedure:
PROCEDURE p_valider_total_ht
IS
too_much exception;
BEGIN
if :jbm_contrat.total_ht > 900 then
raise too_much;
end if;
exception
when too_much then
raise;
when others then
lib_alert(' Exc en f_valider_total_ht ' || to_char(sqlcode) || 'yyy' || sqlerrm );
END;
It works, but the sqlcode contains: 1, wich means I can't distinguish between exceptions cases.
I tried the pragma exception init approach, but then Forms became really cross and threw a very big error message.
Many thanks for your help.Hi,
It looks like pragma exception_init only works for existing Oracle error codes and messages.
I have written a function that returns 'OK' or KO' and the calling trigger raises an exception if 'KO' is returned.
Many thanks. -
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.
Maybe you are looking for
-
Why is my iCloud backup for photos 3.3 Gbs but I only have 12 photos in my camera roll?
After purchasing my iPhone 4S I performed a restore from backup that I had from my iPhone 4 (running iOS 4.3.5). Prior to doing this restore, I did not realize that my photos were not being synchronized from my iOS device and saved in that backup. So
-
We cant seem to get this thing figured out weve tried unsyncing them and that didnt work please help fast i need freedom from my mother stalking my messages!
-
Getting error while running HCM Processes
Hi All, When I am running the HCM Processes using Web Dynpro Application "asr_process_execute" , I am able to get the application. Then I tried to select the Employee , Select the proces, Edit form for that particular process. Once I done with the ch
-
IPlanet J2EE application not working with oracle 9i but working with 7.3
We are in a process of upgrading database from oracle 7.3 to 9i. We have a working application running on iPlanet Application Server with oracle 7.3 as database. We are using iPlanet Application Server's connection pooling. Our JDBC driver is classes
-
Trapcode Form and Particular Z axis issue
I have a problem using trapcode Particular and Form in the same composition ... The emitter of Particular is a light and goes from the front to the back of the composition through Z axis. The particles of the form are in the middle of this travel. Wh