Catching SQL Exceptions
Hi all,
I have a bit of java code which is performing an SQL insert on a table. There is a possibility of a database foreign key exception being generated on this insert statement. I wish to catch this particular exception, log it and then ignore it and move to the next statement. Currently the code is catching SQLException, is a foreign key exception something that I can uniquely catch, or is it rolled up into SQLException. I haven't had luck finding any docs on this subject, any help would be appreciated.
Thanks.
Maybe I'm not understanding something here but is it
not a bit dodgy to be relying on the presence of a
foreign key constraint on the DB to raise the problem
in the client? Personally I would be writing code to
check if a foreign key constraint error will be raised
by the inserting of the record. I will admit though
that this could be a bit clunky and more time
consuming (checking through select statement then
doing insertion if OK) as well as a possible insertion
of the record just after your select statement
returned saying that you couldn't insert the record
because a foreign key constraint would be raised.I disagree. IMHO, the OP's way of doing it is the proper approach--let the database worry about the data integrity. It's made to be very good at that, and that's where the constraints are defined. If you put that code in the client, you have to duplicate the constraints you put into your DDL in your client code.
Similar Messages
-
How to throw or catch sql exception for executeReader sql adapter
Wcf sql adapter was created and executeReader was used.
When an invalid sql statement was constructed and send it to wcf sql adapter, it will hanging there, and no response. No exception was catched even though send chape was inside a catch block. How can I catch this kind of exception
or throw this exception ? I need to give client an exception resposne.
thanks
GaryI used scope with exception handle which has Exception object type: "System.SystemException".
I guess this type "System.SystemException" can catch any exception, including sql exception. Maybe I am wrong. I got error from window event:
A message sent to adapter "WCF-Custom" on send port "WcfSendPort_SqlAdapterBinding_DalCore_Custom" with URI "mssql://shig-quad-2k3e1//DataSourceOne?" is suspended.
Error details: System.Data.SqlClient.SqlException: Incorrect syntax near '='.
Server stack trace:
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndRequest(IAsyncResult result)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System.ServiceModel.Channels.IRequestChannel.EndRequest(IAsyncResult result)
at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.RequestCallback(IAsyncResult result)
MessageId: {B24EF5B8-298A-4D4F-AA98-5E639361A7DB}
InstanceID: {F8924129-265B-4652-B20E-8D25F8F20A51}
If "System.SystemException" can't catch all exception, which type can catch all exception ? I want to catch all exception in this catch block.
thanks
Gary -
Hi,
Is there any other way to catch primary key violation error other than catching the sql exception and checking the pattern in the exception trace.
Thanks in advance,Basil wrote:
Hi,
Is there any other way to catch primary key violation error other than catching the sql exception and checking the pattern in the exception trace.You could try looking at the SQL state or vendor code from the SQL exception. They might have more information, along the lines of what you are looking for.
If you are looking to avoid the exception altogether forget it. You could do a SELECT before INSERT but that of course isn't concurrency "safe" and generally is just a waste of time.
PS In future JDBC related questions should be posted into the JDBC forum. Selecting the best forum for your question gives you a better chance of getting better answers faster. -
How to catch SQL Exceptions in JSP
Hi,
I wanted to know how do we catch the correct SQL return code in a JSP page ?
Based on the return code I wanted to display customised Error messages.
But I could'nt figure out a way to get the error message returned by the underlying DB2
database.
I am using Websphere Application Server and the backend database is DB2.The only way I am aware of is parsing the exception message/the call stack.
-
I'm using oracle 8.1.7
How do I catch a SQL Excpetion from a JSP page that is trying to delete a Primary key of a referencing table?
When it throws the excpetion...how can I know the error code/number?
or is it just simply give out the reason/explanation without producing any numbers?????Hi,
Just put your conde inside a try - catch block like Servlets. It will work and show u all the things.
Sundar -
Catching a particular SQL Exception
Hi
I am getting an SQLException ORA-01653: unable to extend table.
Is there any way so that I can catch this particular exception only.
If I have a catch block
catch(SQLException e)
System.out.println(e);
The above will be general and for all sql exception, I want to only catch ORA 01653 exception
ThanksNo, but what you can do is to test if this is the exception you want to special case in a local try - catch, then rethrow the exception if it's not a match.
-
How to catch up Exception message?
i have a question while using try{ ... }catch{ ... } clauses. for when update, delete, databse, there might be error occurred. all to often i do not deal with the message, only if to check log when serious problem i have to find it out; but i hope to learn how if i am able to display message of my own while erro occurrs. for instance, when falling into SQLException, originaly i might just utilize
}catch(SQLException e){
e.printStackTrace();
is it possible for me to catch up message inside the printStackTrace that may happen while errors appearing? (or only down to catch{} clause be the last deadline that i am able to use? because i hope i am able to capture error code like ora-1234 and tranlate it into messages that user, who doesn't know too much about pc, can understand easily while reporting bug; and not just saying "we have problem here!")
that is, if 'A' situation popping out, i hope to direct it to error page with special message shown. so does the same error page with different message specified while 'B' situation found out!
any suggestions would be appreciated~
thanks in advice,printStackTrace isn't obligatory. It's basically what you do with an exception when you don't have anything more specific to do with it.
You can certainly catch a specific exception at any level, including inside another try {} block.
Even having caught an exception you can decide that you don't want to handle it at this point in the code, and throw it again.
You might do:
try {
try {
... statment which migh cause a particular database exception
} catch(SQLException e) {
if(e.getMessage().startsWith("ORA-1232")) {
.. do somthing usefull
} else
throw e; // the particular SQL exception was unexpected so go on and crash
catch(Exception e) {
e.printStackTrace(); // unexpected program failure -
Pl/sql exception not caught.
This program should give me an error "table or view does not exist" caught by the pl/sql exception, as dba_data_file1 table does not exist.
However all that it returns is Input truncated to 3 characters
Q1. Why?
Q2. How can I remove this message "Input truncated to 3 characters. Where is this message comming from?
#!/bin/ksh
sqlplus -s << EOF
abc/[email protected]
set pages 0
SET SERVEROUTPUT ON BUFFER 100000000
BEGIN
dbms_output.ENABLE(1000000);
SELECT
round(sum(bytes)/1024/1024/1024),
round(sum(free_bytes)/1024/1024/1024),
TRUNC(SYSDATE)
from
(SELECT tablespace_name, BYTES, 0 FREE_BYTES FROM dba_data_files1
UNION ALL
SELECT tablespace_name, 0, BYTES FROM dba_free_space
union all
SELECT tablespace_name, BYTES, 0 FROM dba_temp_files
union all
SELECT 'REDO-LOGS', b.BYTES, 0
FROM v\\$logfile a, v\\$log b
WHERE
a.GROUP# = b.GROUP#);
dbms_output.put_line("ok ");
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line("Error "||SQLERRCODE ||":"|| SQLERRM);
exit 1
END;
exit 0
EOF
$> tstrun.ksh
Input truncated to 3 charactersEXCEPTION
WHEN OTHERS THEN
dbms_output.put_line("Error "||SQLERRCODE ||":"|| SQLERRM);
exit 1
END;
if you catch exception, process it then you must reraise it. its a general mistake found when you are using others instead of name exception, so remember whenever you use others you must reraise the exception -
SQL exception in OAF Controller
Hi
I am getting SQL exception error with the following query in OAF Controller.
Can anyone tell me the issue with the follwoing query,
PreparedStatement cal = conn.createPreparedStatement(" SELECT count(1) " +
" FROM hz_parties hp, hz_cust_accounts_all hca, hz_cust_acct_sites_all hcas " +
" WHERE hca.party_id = hp.party_id " +
" AND hp.party_name = '"+partyName+"'" +
" AND hcas.cust_account_id = hca.cust_account_id " +
" AND hcas.org_id = 14078 " +
" AND oapagecontext.getOrgId() != 14078 ",1);
catch(SQLException sqle)
lcount = String.valueOf(0);
exceptions.add(new OAException("Error in the custom query, Contact Administrator" , OAException.INFORMATION));
OAException.raiseBundledOAException(exceptions);
}Myself fixed by removing the profile org id from query and put it outside
-
Sql exception occurred during pl/sql upload error in custom integrator
Hi,
I have modified custom integrator which was working fine. I have added one column in template and the lov is working fine.
Issue is that when i upload the file to oracle it showing error as ''sql exception occurred during pl/sql upload".
I have tried executing the same from back end but it was working fine from back end and inserting properly in interface table.
Kindly suggest for the issue.
Regards,
GkHi,
You can get the error message in excel sheet itself by using the following piece of code.
FND_MESSAGE.CLEAR;
FND_MESSAGE.SET_NAME ('APPLICATION', 'APPLICATION_MESSAGE_NAME');
FND_MESSAGE.SET_TOKEN ('ERROR_TOKEN', ERROR MESSAGE);
FND_MESSAGE.RAISE_ERROR;
Create an excpetion block and include the above piece of code whilde catching the exception.
APPLICATION- The applicatio in which you create message
APPLICATION_MESSAGE_NAME- The message Name
ERROR_TOKEN- You must create a token in application message
ERROR MESSAGE- You can see the error using SQLERRM.
Thanks,
Vinoop -
Sql exception when connecting to oracle database
When trying to connect to an oracle database using the code below i get an sql error. i put the code below it and the stack trace below the code. any help would be great
Connection connection = null;
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
// Create a connection to the database
String serverName = "192.168.0.2";
String portNumber = "1158";
String sid = "orcl";
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
// String url = "jdbc:oracle:oci:@orcl";
String username = "system";
String password = "mmsi";
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exception in connection to db");
} catch (SQLException e) {
System.out.println("SQL Exception in connecting to Database ");
e.printStackTrace();
stackTrace------------------------------------------------------------------------------
java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
SQL Exception in connecting to Database
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:255)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
before this.start
got to doaction
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:420)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(DriverManager.java:525)
at java.sql.DriverManager.getConnection(DriverManager.java:171)
at mmsiserver.conversation.<init>(conversation.java:190)
at mmsiserver.Server.run(Server.java:105)
Exception in thread "Thread-0" java.lang.NullPointerException
at mmsiserver.conversation.doAction(conversation.java:218)
at mmsiserver.conversation.<init>(conversation.java:202)
at mmsiserver.Server.run(Server.java:105)Message was edited by:
pcpitcher1Please read this
http://forum.java.sun.com/thread.jspa?threadID=512566&start=0&tstart=0 -
How does one catch WebUtil exceptions?
We are automating Microsoft Word using the CLIENT_OLE2 built-in. In some cases, our requirements demand that Word be running in a visible window. One of our processes automates the same Word session repeatedly -- when a user unwittingly closes Word, and our process attempts to further automate the now-closed Word session, exception WUO-714 is raised, and an alert is displayed.
The WebUtil documentation indicates that logging can be configured silently log exceptions without an alert being displayed, but I cannot find a way to actually catch them. Our process could recover gracefully from the scenario described above by simply relaunching Word -- if only we could catch the exception!
Has anyone else already figured out to accomplish this?
Thanks,
Eric Adamson
State of MichiganHerzliche Begrüßen Gerd,
Thanks for your reply -- the error occurs in a PL/SQL block. Since my initial post, I have discovered that my test code contained a WHEN OTHERS THEN NULL statement. (When coding blocks, I often complete them with NULL statements, as I compile very often, to simplify tracking down errors. This strategy works wonderfully, when I remain focused, but the distractions of researching WebUtil errors evidently led me to overlook my mistake. Perhaps others may learn from my embarrassing lesson.)
In any case, I am now able to catch the exception, and to handle it appropriately. Most importantly, readers should note that it was necessary to change the WebUtilErrorMode entry in FORMSWEB.CFG. By default WebUtilErrorMode=Alert -- this causes the error alerts to pop up, regardless of whether/not the exception ultimately gets handled. I have set WebUtilErrorMode=Console.
Thanks for reading, and congratulations on winning the match with Costa Rica!
Regards,
Eric Adamson
Lansing, Michigan -
Hi All,
I have extended the standard CO.
Below is my code.
processRequest(OAPageContext pageContext,OAWebBean webbean)
super.processRequest(pageContext,webbean);
processFormRequest(OAPageContext pageContext,OAWebBean webbean)
super.processRequest(pageContext,webbean);
String evt = pageContext.getParameter(OAWebBEanConstants.EVENT_PARAM);
OAApplicationModule oaapplicationmodule = pageContext.getRootApplicationModule();
OAViewObject vo = (OAViewObject)oaapplicationmodule.findViewObject("DisplaydetailsVO");
if(vo!=null)
vo.first();
String fwk = pageContext.getParameter("Runid"); *// If i use this statement to call the attribute value then Error 1 i am getting*
(or)
String qaz = (String)vo.getCurrentRow().getAttribute("Runid") *// If i use this statement to call the attribute value then Error 2 i am getting*
if(event.equals("GO")
try
CallableStatement callablestatement = (oracleCallableStatement)oaapplicationmodule.getOADBTransaction().createCallableStatement("begin purchase_po_wf.purchasing_vision_wf(:1); end;",1);
callablestatement.execute();
callablestatement.setString(1,fwk);
callablestatement.setString(1,qaz);
callablestatement.close();
callablestatement.close();
Catch(SQLException ex)
Please suggest me which statement to use call the Attributes & VO . Please do let me know if anything is wrong in the code.
I am getting the below errors :
1. Cannot call the procedurejava.lang.sql.exception Method in & out parameters extends::1
2. Java.lang.NullPointerException
Can any one please help me out , to overcome this issue. Its bit urgent
Thanks,
KalyanHi Kalyan,
So you want to get the value of DisplaydetailsVO.Runid attribute
and then use it for calling a package?
and the attribute is Runid or RunId
you can put the below code to get all the attributename and its values in the VO.(change the VO, AM names according to your customizations)
Then you can get what should be attributeName you should be using it, and I am not sure about your requirement, you might need to call before super.processFormRequest().
Get all the attribute from a VO with Attribute Names in Custom CO
OAApplicationModule rootAM = pageContext.getRootApplicationModule();
OAApplicationModule apprAM = (OAApplicationModule)rootAM.findApplicationModule("AppraisalsAM");
String offlineStatus = (String)apprAM.invokeMethod("getOfflineStatus",new Serializable[]{appraisalId+""});
OAViewObject appraisalVO = (OAViewObject)apprAM.findViewObject("AppraisalVO");
if(appraisalVO !=null)
AppraisalVORowImpl appraisalVORow = (AppraisalVORowImpl) appraisalVO.first();
if(appraisalVORow !=null)
int attrCount = appraisalVO.getAttributeCount();
writeLog("XXRBG",pageContext,"Attrbuute count "+attrCount);
String[] attributeNames = appraisalVORow.getAttributeNames();
for (int i = 0 ;i< attributeNames.length ;i++ )
writeLog("XXRBG",pageContext," Name "+attributeNames[i] +" = "+appraisalVORow.getAttribute(i));
Thanks,
With regards,
Kali.
OSSi. -
Bug? EJB method Return Value and Client Catch the Exception?
oc4j 9.0.3 on the windows 2000
I write a Stateless Session Bean named SB1 ,
and define application exception.
The Code as follow:
public class AppErrorException extends Exception
public interface SB1 extends EJBObject
public String getMemono(String sysID, String rptKind, String parentMemono)
throws RemoteException, AppErrorException;
public class SB1Bean implements SessionBean
public String getMemono(String sysID, String rptKind, String parentMemono)
throws RemoteException, AppErrorException
throw new AppErrorException("Error in getMemono");
public class SB1TestClient
try
memomo= sb1.getMemono(.....);
catch(AppErrorException ae)
ae.printStackTrace();
I found a bug.
If SB1.getMemono() throws the AppErrorException, but SB1TestClient will not catch any Exception.
It is not normal!!!!
[cf]
But If I convert "public String getMemono(...)" into "public void getMemono(...)",
When SB1.getMemono() throws the AppErrorException, but SB1TestClient will catch any Exception.
It is normal.getMemono(.......)'s code as follow:
public String getMemono(String sysID, String rptKind, String parentMemono)
throws AppErrorException
log("getMemono("+sysID+", "+rptKind+", "+parentMemono+")");
Connection connection= null;
CallableStatement statement = null;
String memono= "";
short retCode= -1;
String retMsg= "";
try
String sql= this.CALL_SPGETMEMONO;
connection = ResourceAssistant.getDBConnectionLocal("awmsDS");
statement= connection.prepareCall(sql);
statement.setString(1, sysID.trim());
statement.setString(2, rptKind.trim());
statement.setString(3, parentMemono.trim());
statement.registerOutParameter(4, java.sql.Types.VARCHAR);
statement.registerOutParameter(5, java.sql.Types.SMALLINT);
statement.registerOutParameter(6, java.sql.Types.VARCHAR);
statement.executeQuery();
retCode= statement.getShort(5);
retMsg= statement.getString(6);
log("retCode="+retCode);
log("retMsg="+retMsg);
if (retCode==AppConfig.SHORT_SP_RETCODE_FAILED)
log("retCode==AppConfig.SHORT_SP_RETCODE_FAILED");
this.sessionContext.setRollbackOnly();
throw new AppErrorException(retMsg);
memono= statement.getString(4);
log("memono="+memono);
if (rptKind.trim().length()<6)
log("rptKind.trim().length()<6");
this.sessionContext.setRollbackOnly();
throw new AppErrorException("rptKind.trim().length()<6");
memono= "SS";
catch (AppErrorException ae)
log("catch(AppErrorException ae)");
throw ae;
//throw new EJBException(ae.getErrMsg());
catch (Exception e)
log("catch (Exception e)");
this.sessionContext.setRollbackOnly();
throw new AppErrorException(IExceptionConst.ERR_MSG_SYSMEMONO_00000, e.toString());
//throw new EJBException(IExceptionConst.ERR_MSG_SYSMEMONO_00000+", "+e.toString());
finally
log("this.sessionContext.getRollbackOnly()="+this.sessionContext.getRollbackOnly());
ResourceAssistant.cleanup(connection,statement);
return memono; -
HI, how can i catch sql system exceptions? ( Catch System-Exceptions.)
with the insert, modify, update sentences
Where can i find a list with the sql catchable exceptions?
ThanksIf you do F1 on CATCH, you can get a list of catchable exceptions.
Rob
Maybe you are looking for
-
Export and Import table in Oracle 8i
Hi Gurus, I want to do an export of a oracle table to a binary file which is in 8i for back up. And at some point of time import the same. Can anyone please guide me the steps for the same. I am using SQL*plus & toad. Thanks in advance.
-
Photos from iphone/ipad not automatically showing up in iPhoto on Mac
Running iOS 8.1 on iPhone 6 and iPad. Running Yosemite on Mac. Photos taken on the iPhone transfer automatically to the iPad but not to iPhoto on the Mac. Photostream is turned on. iCloud Photo Library Beta is not turned on. This worked before Y
-
Ok, guys i have a question which sounds really ridiculous but as a new mac user, i cant stop thinking about it. Recently, i just bought my macbook air 13 inch. Yesterday, my wife was using it and she constantly used her fingers to drum around the are
-
Sum of calculated key figures in a report
Hi, i have the following report : Country percent FR 0% SP 100% GE 100% UK 100% I want to display at end a line with : sum percent / number of country The result should be : 300/4 = 75% bu
-
I am trying to install AIA Demo on Windows XP. The version I am trying to install is 2.2.1. Getting the following error. [exec] deploy: [exec] [echo] =============D:\oracleaia\AIAHOME/util/DeployTool/AIABuild.properties============= [exec] [exec] run