Try catch + wait in pl/sql?
what are possible approaches to write procedure that:
1) tries to make update/merge
2) if update/merge fails for any reason then it waits 10s and tries again
3) maximum allowable trial counter is 6
4) if it cannot do update/merge without an error during those 6 attempts it finishes and passes original error code to the application
I would appreciate your suggestion about coding such procedure.
thank you
943276 wrote:
what are possible approaches to write procedure that:
1) tries to make update/merge
2) if update/merge fails for any reason then it waits 10s and tries again
3) maximum allowable trial counter is 6
4) if it cannot do update/merge without an error during those 6 attempts it finishes and passes original error code to the application
I would appreciate your suggestion about coding such procedure.Procedures. Plural. Structured and modularised programming. Non-negotiables ito writing robust, maintainable and flexible code. And the above logic needs more than one code unit.
From a pure coding perspective, writing this is not a problem. DBMS_LOCK is used for sleeping a number of seconds. A loop and a counter is needed to control loop execution. An exception handler in the loop for handling loop logic (successful iteration, another iteration, throw error up call stack).
However, from a software engineering perspective I do not see this as a solution. It is a hack. A very poor hack at that... attempting to fix a problem via addressing the symptoms.
Why would the merge fails? Why will waiting 10 seconds "fix" the cause of the failure? Why hit the same brick wall repeatedly (up to 6 times), spending expensive server resources in doing that?
I would rather determine the actual problem and address that, instead of putting a hack in place trying the Large Hammer approach...
Similar Messages
-
How to simulate a dml error in order to test try-catch code block inside a stored procedure
Hi,
What would be the easiest way to simulate a dml error in order to test a try catch block.
I would like to do it with a simple command from outside the stored procedure if possible.
I tried dropping the table that was updated but it hangs
Thanks,
DaniDropping the table that is the target of the procedure will give you an unpleasant surprise: the CATCH block will not fire. To wit, errors like missing tables can only be caught in outer scopes, but not in the procedure where the error occurs.
But you would add a fake constraint to a table which causes the update to fail. You need to do this in advance, not while running the procedure.
Erland Sommarskog, SQL Server MVP, [email protected] -
Dear all,
Can any body clear me what is code for try catch in SAP 4.6C? I tried the below code but the object type is doesn't exist. ( cx_root or x_sy_native_sql_error)
DATA: exc_ref TYPE REF TO cx_root, " cx_sy_native_sql_error,
error_text TYPE string.
LOOP AT it_sqlupdate.
try.
EXEC SQL.
insert into TBLSVBALSAP
( CoCode, SAPDocNo, PostDate, DocHdrTxt, GLAccount,
Amount, Text, RevDoc, CreationDate, CreationTime ) values
( :it_sqlupdate-c_code, :it_sqlupdate-sap_docno, :it_sqlupdate-p_date,
:it_sqlupdate-h_text, :it_sqlupdate-gl_acc, :it_sqlupdate-amt,
:it_sqlupdate-i_text, :it_sqlupdate-r_docno, :it_sqlupdate-c_date,
:it_sqlupdate-c_time )
ENDEXEC.
catch cx_sy_native_sql_error into exc_ref.
error_text = exc_ref->get_text( ).
MESSAGE error_text type 'I'.
endtry.
ENDLOOP.
Thanks.Hi,
I think, TRY CATCH Exception concept was not there in 4.6C, alternatively you can try with
CATCH SYSTEM-EXCEPTIONS.
Check the link below
http://help.sap.com/abapdocu/en/ABAPCATCH_SYS.htm
regards
Mahesh -
Catching jsp/tomcat/java SQL error
I have been trying to get the sample code to work from an old book. I was finally able to get it to run under tomcat 4.1.31 but there is one bug I just cannot figure out how to handle. I am a beginner to Java/JSP/Tomcat and have about 16+ hours invested in this problem so far.
The delFruit.jsp calls methods from FruitConnect.java.
I found that if the fruit chosen for deletion was not involved in a referential integrity link to a FruitMonth file the code works fine. But if it is linked the delFruit.jsp just displays a blank screen and nothing is deleted. It is fine for it not to be deleted but I cannot find anyway to handle it. I tried to add the checkFruitForSale bandaid below but it causes me a blank screen as well.
Any help would be appreciated.
It would be great if I could just see what is happening when FruitConnect is processing code. I get no errors, just a blank screen. I'm going to try using NetBeans and their debugger next.
Here is delFruit:
<%@ page import="java.sql.*" %>
<jsp:include page="adminHeader.html" flush="true" />
<jsp:useBean id="fruitConnect" class="fruit1.FruitConnect" />
<%
String msg = "The following fruits have been deleted:<br> ";
//Build the list of fruits to delete
String delFruit[] = request.getParameterValues("delFruit");
//WE WILL ONLY GET CHECKBOXES THAT WERE CHECKED
String fruitList = "";
if (delFruit != null){
int len = delFruit.length;
fruitConnect.dbConnect();
for (int i = 0; i < len; i++) {
String passfruit = delFruit;
if (fruitConnect.checkFruitForSale(passfruit)) {}
else{
fruitList = fruitList + "'" + delFruit[i] + "',";
msg = msg + delFruit[i] + "<br>";
out.print(msg);
out.print(msg);
fruitList = fruitList + "'nonsense'";
if (fruitConnect.deleteFruit(fruitList) < 1) {
msg = "There was an error deleting the fruits from the database.";
else{
msg = "Deletion was successful";
fruitConnect.dbDisconnect();
else {
msg = "You must select some fruit to delete.";
%>
HERE IS FruitConnect.java
package fruit1;
import java.sql.*;
public class FruitConnect {
private Driver drv = null;
private Connection conn = null;
private ResultSet rs = null;
private Statement stmt = null;
public FruitConnect(){}
public void dbConnect() throws Exception{
// drv = (Driver) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// conn = DriverManager.getConnection("jdbc:odbc:Fruit");
try{
drv = (Driver) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
conn = DriverManager.getConnection("jdbc:odbc:Fruit");
catch ( SQLException sqlException)
sqlException.printStackTrace();
finally
try{
catch (Exception exception)
public boolean getNextItem() throws Exception{
boolean ret = rs.next();
return(ret);
public String getItemNameString(String columnName) throws Exception{
String name = rs.getString(columnName);
return(name);
public float getItemNameFloat(String columnName) throws Exception{
float name = rs.getFloat(columnName);
return(name);
public boolean selectFruits() throws Exception{
String query = "SELECT Id, Name FROM Fruit";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
boolean ret = false;
if (rs != null)
ret = true;
return(ret);
public boolean selectMonths() throws Exception{
String query = "SELECT Id, Name FROM Month";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
boolean ret = false;
if (rs != null)
ret = true;
return(ret);
public boolean selectFruitForSale() throws Exception{
String query = "SELECT F.Name AS Fruit, M.Name AS Month, Price, Weight, (Price * Weight) AS TotalPrice FROM FruitMonth AS FM, Fruit AS F, Month AS M WHERE FM.FruitId = F.Id AND FM.MonthId = M.Id ORDER BY M.Id";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
boolean ret = false;
if (rs != null)
ret = true;
return(ret);
public int insertFruit(String name) throws Exception{
String query = "INSERT INTO Fruit (Name) VALUES ('" + name + "')";
stmt = conn.createStatement();
int ret = stmt.executeUpdate(query);
return(ret);
public int insertFruitForSale(String insertValues) throws Exception{
String query = "INSERT INTO FruitMonth (FruitId, MonthId, Price, Weight) VALUES (" + insertValues + ")";
stmt = conn.createStatement();
int ret = stmt.executeUpdate(query);
return(ret);
public int deleteFruit(String fruitList) throws Exception{
String query = "DELETE FROM Fruit WHERE Name IN (" + fruitList + ")";
stmt = conn.createStatement();
int ret = stmt.executeUpdate(query);
return(ret);
public void dbDisconnect() throws Exception{
stmt.close();
conn.close();
public boolean checkFruitForSale(String thisfruit) throws Exception{
String query = "SELECT F.Name AS Fruit, M.Name AS Month, Price, Weight, (Price * Weight) AS TotalPrice FROM FruitMonth AS FM, Fruit AS F, Month AS M WHERE FM.FruitId = F.Id AND FM.MonthId = M.Id AND F.Name IN (" + thisfruit + ") ORDER BY M.Id";
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
catch ( SQLException sqlException)
sqlException.printStackTrace();
boolean ret = false;
if (rs != null)
ret = true;
return(ret);
finally
try{
catch (Exception exception)
boolean ret = false;
if (rs != null)
ret = true;
return(ret);
public String Check1(String columnName) throws Exception{
String name = rs.getString(columnName);
return(name);First thing to check would be the Tomcat log file. Most likely there is an error message printed there:
Look in [TOMCAT]/logs for any files modified recently. Open it, and you should find some hints as to your error.
It would be great if I could just see what is happening when
FruitConnect is processing code.For that sort of thing, you want to use a logger. Either Log4J or the standard Java1.4 logger would help. Basically configure it to log statements to file as your program runs.
I get no errors, just a blank screenThat could indicate that the page ran enough to fill up the page buffer, and then failed. When you view source, do you see anything on the page at all? -
TRY CATCH with dynamic ORDER BY
Some stored procs need a dynamic ORDER BY, unfortunately.
Can I use a TRY CATCH with ORDER BY?
SELECT ...
FROM ...
WHERE...
BEGIN TRY
ORDER BY ...complex stuff
END TRY
BEGIN CATCH
ORDER BY ColumnA
END CATCHHi mmmtbig,
Syntactically, it is ok to use any valid sql statement in the TRY AND CATCH block.
SELECT 1 as num
BEGIN TRY
SELECT 1/0 AS seq UNION SELECT 2 ORDER BY seq;
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE();
SELECT 1 AS seq UNION SELECT 2 ORDER BY seq;
END CATCH
For more details, You can reference
TRY...CATCH.
The confusion about your question is the "dynamic ORDER BY". What do you mean by that, can you elaborate your requirement, like in what scenario you'd like to use the code block in your post and what issue have stopped you from doing that?
If you have any feedback on our support, please click
here.
Eric Zhang
TechNet Community Support -
Can't find class because of try catch block ?!
Hello,
I'm using the JNI to use a java library from my c++ code.
JNI can't find the "Comverse10" class below, but when i put the try catch block in createMessage in comment, FindClass succeeds ?!
Unfortunatly i need the code inside the try block ;-)
I tried a few things, but none of them worked:
- let createMessage throw the exception (public void createMessage throws ElementAlreadyExistsException ), so there isn't a try catch block in createMessage => result: the same
- make a "wrapper" class Comverse that has a Comverse10 object as attribute and just calls the corresponding Comverse10.function. Result: Comvers could be found, but not constructed (NewObject failed).
Can someone tell me what is going on ?!
Thank you,
Pieter.
//Comverse10 class
public class Comverse10 {
MultimediaMessage message;
/** Creates a new instance of Comverse10 */
public Comverse10() {
public void createMessage() {
TextMediaElement text1 = new TextMediaElement("Pieter");
text1.setColor(Color.blue);
SimpleSlide slide1 = new SimpleSlide();
//if i put this try catch block in comment, it works ?!
try{
slide1.add(text1);
catch(com.comverse.mms.mmspade.api.ElementAlreadyExistsException e){}
MessageContent content = new MessageContent();
content.addSlide(slide1);
this.message = new MultimediaMessage();
message.setContent(content);
message.setSubject("Mijn subjectje");
for those of you who are intersted: here's my C++ code:
//creation of JVM
HRESULT Java::CreateJavaVMdll()
HRESULT HRv = S_OK;
char classpath[1024];
jint res;
if(blog) this->oDebugLog->Printf("CreateJavaVMdll()");
strcpy(classpath,"-Djava.class.path="); /*This tells jvm that it is getting the class path*/
strcat(classpath,getenv("PATH"));
strcat(classpath,";D:\\Projects\\RingRing\\MMSComposer;C:\\Progra~1\\j2sdk1~1.1_0\\lib"); //;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mail.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\activation.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mmspade.jar
//------Set Options for virtual machine
options[0].optionString = "-Djava.compiler=NONE"; //JIT compiler
options[1].optionString = classpath; //CLASSPATH
//------Set argument structure components
vm_args.options = options;
vm_args.nOptions = 2;
vm_args.ignoreUnrecognized = JNI_TRUE;
vm_args.version = JNI_VERSION_1_4;
/* Win32 version */
HINSTANCE hVM = LoadLibrary("C:\\Program Files\\j2sdk1.4.1_01\\jre\\bin\\client\\jvm.dll");
if (hVM == NULL){
if(blog) oDebugLog->Printf("Can't load jvm.dll");
return E_FAIL;
if(blog) oDebugLog->Printf("jvm.dll loaded\n");
LPFNDLLFUNC1 func = (LPFNDLLFUNC1)GetProcAddress(hVM, "JNI_CreateJavaVM");
if(!func){
if(blog) oDebugLog->Printf("Can't get ProcAddress of JNI_CreateJavaVM");
FreeLibrary(hVM); hVM = NULL;
return E_FAIL;
if(blog) oDebugLog->Printf("ProcAddress found");
res = func(&jvm,(void**)&env,&vm_args);
if (res < 0) {
if(blog) oDebugLog->Printf("Can't create JVM with JNI_CreateJavaVM %d\n",res);
return E_FAIL;
if(blog) oDebugLog->Printf("JVM created");
return HRv;
//finding Comverse10 class:
HRESULT CALLAS MMSComposer::InitializeJNI(void)
HRESULT HRv=E_FAIL;
DWORD T=0;
try
if(blog) oDebugLog->Printf("\nInitializeJNI()");
bJVM = FALSE;
jni = new Java(oDebugLog);
if(jni->CreateJavaVMdll()!=S_OK){
if(blog) oDebugLog->Printf("CreateJavaVMdll() failed");
return HRv;
jclass jcls = jni->env->FindClass("Comverse10");
if (jcls == 0) {
if(blog) oDebugLog->Printf("Can't find Comverse10 class");
jclass jcls2 = jni->env->FindClass("test");
if (jcls2 == 0) {
if(blog) oDebugLog->Printf("Can't find test class");
return HRv;
if(blog) oDebugLog->Printf("test class found %08x",jcls2);
return HRv;
if(blog) oDebugLog->Printf("Comverse10 class found %08x",jcls);
jmethodID mid = jni->env->GetMethodID(jcls , "<init>", "()V");
if (mid == 0) {
if(blog) oDebugLog->Printf("Can't find Comverse10() constructor");
return HRv;
if(blog) oDebugLog->Printf("Comverse10() constructor found");
jobject jobj = jni->env->NewObject(jcls,mid);
if(jobj==0)
if(blog) oDebugLog->Printf("Can't construct a Comverse10 object");
return HRv;
if(blog) oDebugLog->Printf("Comverse10 object constucted");
//Create Global reference, so java garbage collector won't delete it
jni->jobj_comv = jni->env->NewGlobalRef(jobj);
if(jni->jobj_comv==0)
if(blog) oDebugLog->Printf("Can't create global reference to Comverse10 object");
return HRv;
if(blog) oDebugLog->Printf("global reference to Comverse10 object %08x created",jni->jobj_comv);
bJVM=TRUE;
HRv=S_OK;
} catch( IDB * bgError ) { throw bgError->ErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T); }
catch(...) { throw IDB::NewErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T ); }
return HRv;>
I would guess that the real problem is that that the
exception you are catching is not in the class path
that you are defining.Thanks jschell, that was indeed the case.
I don't have the docs, but I would guess that
FindClass() only returns null if an exception is
thrown. And you are not checking for the exception.
Which would tell you the problem.Ok, i'll remember that. But what with exceptions thrown in my java code, the documents say
// jthrowable ExceptionOccurred(JNIEnv *env);
// Determines if an exception is being thrown. The exception stays being thrown until either the native code calls ExceptionClear(), or the Java code handles the exception
so, what if the java code throws an exception and catches it, will i be able to see that in my c++ code with ExceptionOccurred ?
or
should the java method be declared to throw the exception (and not catch it inside the method)
Again, thank you for your help, it's greatly appreciated ! -
How to get the returned error messages in the Try/Catch block in DS 3.0?
A customer sent me the following questions when he tried to implement custom error handling in DS 3.0. I could only find the function "smtp_to" can return the last few lines of trace or error log file but this is not what he wants. Does anyone know the answers? Thanks!
I am trying to implement the Try/Catch for error handling, but I have
hard time to get the return the msg from DI, so I can write it to out
custom log table.
Can you tell me or point me to sample code that can do this, also, can
you tell me which tables capture these info if I want to query it from
DI system tablesHi Larry,
In Data Services XI 3.1 (GAd yesterday) we made several enhancements for our Try/Catch blocks. One of them is the additional of functions to get details on the error that was catched :
- error_message() Returns the error message of the caught exception
- error_number() Returns the error number of the caught exception
- error_timestamp() Returns the timestamp of the caught exception.
- error_context() Returns the context of the caught exception. For example, "|Session Datapreview_job|Dataflow debug_DataFlow|Transform Debug"
In previous versions, the only thing you could do was in the mail_to function specify the number of lines you want to include from the error_log, which would send the error_log details in the body of the mail.
Thanks,
Ben. -
Can we have try/catch in a static block in a class?
hi All
i have a question about put a try/catch block in a static block in a class to catch exceptions that maybe thrown from using System.xxxx(). in my custom class, i have a static block to initialize some variables using System.xxx(). in case of any error/exception, i need to be able to catch it and let the caller know about it. i tried to put a try/catch block in the static block, and tried to rethrow the exception. but it is not allowed, how would i handle situation like this? thanks for your help and advise in advance.You could just swallow the exception inside try/catch
block, and instead of throwing it out, just set a
static variable to allow checking from outside
whether the initialization succeeded, or check within
the constructor / methods of this class for
successful initialization, and throw the exception
then. You could even save that exception in a static
variable for later.Ouch, ouch, you're hurting my brain. This would allow someone to ignore a (presumably) fatal error. Throw a RuntimeException as indicated. You can wrap a checked exception in an unchecked one if need be. -
RAISERROR with Try/Catch does not exit after exception in catch block
I am trying to propogate an error from within my proc out to the caller.
In the attached example I have 2 sets of try catch blocks.
I raiserror in the first
catch the error and then raiserror again. (I expect to exit)
I do not expect :
to get to print 'post test'
to get to second try block.
but this does not exit, instead the code flows as per 2 runs.
I do not understand the reason for the flows, as it seems counterintuitive to be raising an error but then still print following exceptions. I cannot seem to find any references that explains this behaviour.
running tests together results
print '-------------------------------------------------------'
print 'test 15'
exec test_raiseerror 15
print '-------------------------------------------------------'
print 'test 16'
exec test_raiseerror 16
print '-------------------------------------------------------'
print 'test 17'
exec test_raiseerror 17
print '-------------------------------------------------------'
print 'test 18'
exec test_raiseerror 18
print '-------------------------------------------------------'
'RESULTS'
test 15
error number provided: 15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
name hello 15
post test
15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
name hello 2 15
post test2
test 16
error number provided: 16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
name hello 16
post test
16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
name hello 2 16
post test2
test 17
error number provided: 17
post test
17
post test2
test 18
error number provided: 18
post test
18
post test2
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
name hello 17
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
name hello 2 17
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
name hello 18
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
name hello 2 18
run tests seperately
exec test_raiseerror 15
error number provided: 15
RESULTS 15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
name hello 15
post test
15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
name hello 2 15
post test2
exec test_raiseerror 16
RESULTS 16
error number provided: 16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
name hello 16
post test
16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
name hello 2 16
post test2
exec test_raiseerror 17
RESULTS 17
error number provided: 17
post test
17
post test2
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
name hello 17
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
name hello 2 17
exec test_raiseerror 18
RESULTS 18
error number provided: 18
post test
18
post test2
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
name hello 18
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
name hello 2 18
CODEBLOCK:
if object_id('test_raiseerror','P') is not null
drop proc test_raiseerror
go
create proc test_raiseerror(@id as int) as
begin
begin try
declare @name varchar(20)
select @name = 'hello'
raiserror('name %s %d',@id,1,@name,@id)
print 'next'
end try
begin catch
declare @errormessage nvarchar(4000)
declare @errornum int
select @errormessage = error_message()
, @errornum = error_severity()
print 'error number provided: ' + convert(varchar(2),@errornum)
raiserror(@errormessage, @errornum,1)
print 'post test'
end catch
begin try
select @name = 'hello 2'
raiserror('name %s %d', @id,1,@name, @id)
end try
begin catch
select @errormessage = error_message()
, @errornum = error_severity()
print @errornum
raiserror(@errormessage, @errornum,1)
print 'post test2'
end catch
end
go
sqlserver 2008 & 2008 R2There is a Connect that describes a similiar complaint. But basically a raiserror inside a catch block does not terminate the procedure, it will continue with any additional code in the CATCH and FINALLY unless it hits a return statement.
http://connect.microsoft.com/SQLServer/feedback/details/275308/have-raiserror-work-with-xact-abort -
Exception handling with try/catch in acrobat
Hi
I have a problem using a try/catch block in my acrobat document-script. Try to enter the following into the debugger-console:
try{nonexistentFunction();}catch(e){console.println('\nacrobat can't catch')}
and run it. The output will be:
nonexistentFunction is not defined
1:Console:Exec
acrobat can't catch
true
The whole point of a rty/catch block is for the application NOT to throw an exception, but instead execute the catch-part of the statement. However, acrobat does both: It throws an exception AND executes the catch-block.
Is there another way to suppress the exception, or to make the try/catch-block work as it's supposed to?> Also Adobe provides for free the JS or compiled file for Acrobat Reader to support the JS console.
Where is that file located ? How to install it or where to place it ?
What is the method referred by try67 on his site where he sells a product ?
Is that the same as the compiled file you refer to ? or did he sell his solution to adobe ?
It is helpful if people can get an idea of the nature of choices available and make informed decisions, than a cloak and dagger approach.
For some jobs that we have, I have been very frustrated by a consultant who wont even give basic info for transparent billing despite all assurances for privacy, as a result we are forced to do the job ourselves.
Dying Vet -
About the finally block of the try catch.
I know that finally block contains the code that will be executed in any condition of the try catch.
However, I think it is unneccessary, since the stack after the try catch stack will be executed any way.
Any one can help?
for example
try{
System.in.read();
catch(Exception e){}
finally
{ System.out.println("does this matter?");}and
try{
System.in.read();
catch(Exception e){}
System.out.println("does this matter?");However, I think it is unneccessary, since the stackafter the try catch
stack will be executed any way.That does assume that you catch and handle the error
appropriately.
Of course this is valid as well, and demonstrates
when you would WANT a finally clause.
Connection con = null;
Statement stmt = null;
try{
con = Database.getConnection();
stmt = con.createStatement("Select * from dual");
// maybe something throws an exception here?
finally{
if (stmt != null){
stmt.close();
if (con != null){
con.close();
The finally block here might throw a null pointer exception itself use
null!=stmt null!=stmt -
Return statement should put beyond try/catch clause??
The return statement should put beyond the try/catch clause, is that correct? Well,
I tried to put inside the try block, but it will have compile error though.
public String getValue()
String value;
try
catch(...)
return value;
please advise. thanks!!When a method returns a value, you must make sure that even if an exception is thrown and caught a value will be returned (or just throw the exception out of the method).
You can put a return clause as the last thing in the try block and another return clause after the catch block (this is where we go if we catch an exception so you probably want to return null). -
Return statement and Try Catch problem
Hi!!
I've got the next code:
public ResultSet DBSelectTeam(String query) {
try {
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(query);
return rs;
} catch (Exception err) {
JOptionPane.showMessageDialog(null, "ERROR: " + err);
But I need a return statement in the catch-block, but I don't know what's the best option.
Help...
Many thanks.The error message is: "missing return statement", Yes, I know.
You have to either return from the catch statement, or throw from the catch statement, or return or throw after the catch statement.
The only ways your method is allowed to complete is by returning a value or throwing an exception. As it stands, if an exception is thrown, you catch it, but then you don't throw anything and you don't return a value.
So, like I said: What would you return from within or after catch? There's no good value to return. The only remotely reasonable choice would be null, but that sucks because now the caller has to explicitly check for it.
So we conclude that catch shouldn't return anything. So catch must throw something. But what? You could wrap the SQLE in your own exception, but since the caller is dealing with JDBC constructs anyway (he has to handle the RS and close it and the Statement), there's no point in abstracting JDBC away. Plus he has to deal with SQLE anyway in his use of the RS and Statement. So you might as well just throw SQLE.
So since you're going to just throw SQLE anyway, just get rid of the try/catch altogether and declare your method throws SQLException -
I have a SCCM 2012 SP1 CU4 environment with SCOM monitoring installed.
I also do have 4 secondary sites installed below my primary. The secondaries are using SQL 2012 Express version default deployed using the secondary site installation.
My SCOM monitoring is generating tickets with the following message:
The Average Wait Time of SQL instance "CONFIGMGRSEC" on computer "<SEC_SITE_SERVER>" is too high
How can i solve this ? Or do I need to ignore this ?Never ignore messages, but tune them.
In this specific case you might want to take a look at this:
http://social.technet.microsoft.com/Forums/en-US/ffeefe0d-0ef7-49a3-862e-9be27989dc5d/scom2012-alert-sql-2008-db-average-wait-time-recompilationis-too-high?forum=operationsmanagergeneral
My Blog: http://www.petervanderwoude.nl/
Follow me on twitter: pvanderwoude -
How to accept 2 strings in a class with try catch method..help!!
the program below will accept two strings and compare str1 and str2 if equal. this program uses functions. can any one help me with this?
import java.io.*;
public class StrCompare {
private BufferedReader takyoin = null;
//private BufferedReader intakyo = null;
* @param args
public StrCompare(){
takyoin = new BufferedReader(new InputStreamReader(System.in));
//intakyo = new BufferedReader(new InputStreamReader(System.in));
public String UserInput(){
public static void main(String[] args) {
// TODO Auto-generated method stub
}What are you talking about? There is no such thing as "try-catch-methods", and there are no functions but methods.
Strings by the way have their own means of comparision. Apart from that: do your own homework.
Maybe you are looking for
-
How to enter a birthday versus a birth date into iPhone contacts
Hi, I sync my contacts with Yahoo!. For many people in my contancts I know their birthday (for example, December 5th), but not their full birth date (for exmaple, December 5, 1975). The iPhone doesn't seem to have an option that lets me put the year
-
RAC Health Check - quick tips please
If in 1 hour time, I have to health check 2 node RAC on windows, what should I start with and what are the important things to check and report related to performance.
-
Went through the discussion on this at Java and Mac. Keep linking me back to the same download. Someone Help!
-
Proper support for Fuji EXR Raw Files
There is still no proper support for Fuji EXR Raw files. On any Fuji X-series camera, the in-camera raw processing, including specifying options always outputs a far superior image that Adobe Camera Raw 6. I've been using an X100 for some time now
-
Hi, Would it be possible to get a Linux PPC version please of Oracle 8i ? Winton