472,353 Members | 1,418 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,353 software developers and data experts.

jython and java exceptions

Hello

I found that jython catches exact java exceptions, not their
subclasses. Is there some way to get around this limitation (or error) ?

My program has class representing database source and specialed classes
for particulars databases. Now there are two options - to include
exception (subclasses of SQLException) for every db in except (so
all drivers has to be present) or to move methods to subclasses.
Jan
Jul 18 '05 #1
7 12492
[Jan Gregor]
I found that jython catches exact java exceptions, not their
subclasses. Is there some way to get around this limitation (or error) ?
Hmm, not sure what you mean here. Consider the following code

#################
from java.io import FileInputStream
from java.io import IOException
from java.io import FileNotFoundException; # Subclasses IOException

dud_file_name = "does_not_exist.txt"

def open_file(filename):
return FileInputStream(filename)

# For this function, we expect the FileNotFoundException clause
# to be executed, because it is listed first, and matches the
# exception precisely

def catch_subclass():
try:
f = open_file(dud_file_name)
f.close()
except FileNotFoundException, fnfx:
print "Caught expected FileNotFoundException: %s" % str(fnfx)
except IOException, iox:
print "Error: should not have reached IOException clause"

# For this function, we expect the IOException clause to be
# executed, because it is listed first, and matches the exception,
# because FileNotFoundException is a subclass of IOException

def catch_superclass():
try:
f = open_file(dud_file_name)
f.close()
except IOException, iox:
print "Caught expected IOException: %s" % str(iox)
except FileNotFoundException, fnfx:
print "Error: should not have reached FileNotFoundException clause"

if __name__ == "__main__":
catch_subclass()
catch_superclass()
########################

AFAICT, the above code demonstrates the correct behaviour for java
exception handling in jython, and contradicts your statements above.

Perhaps you can post a code sample that shows what you mean?
My program has class representing database source and specialed classes
for particulars databases. Now there are two options - to include
exception (subclasses of SQLException) for every db in except (so
all drivers has to be present) or to move methods to subclasses.


You should be able to catch all exceptions using code like this

try:
# database operations
except java.sql.SqlException:
# This will catch all SQLExceptions and subclasses.

--
alan kennedy
------------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan: http://xhaus.com/contact/alan
Jul 18 '05 #2
Hello
I tried it again with SQLException only but my main loop ends with
uncatched com.sybase.jdbc2.jdbc.SybSQLException. This is extract from my code, exception is thrown by self.db.executeSql(iline),
def run (self):
while (1):
gr_mode= 0
iline= Readline.readline(":", 0)
if iline==None:
continue
iline= strip(iline)
if iline=='\q':
try:
Readline.writeHistoryFile(self.rl_history.getName( ))
except:
print ("Error writing history file!")
System.exit(0)
break
if iline=='\gr':
continue Readline.addToHistory(iline) if re.match(r'^\+ ', iline):
gr_mode= 1
iline= strip(iline[2:])

try:
type, result= self.db.executeSql(iline)
if result==None:
continue
if type=='resultSet':
self.process(result)
elif type=='table':
if gr_mode:
wnd = swingWnd.SimpleSwing(result.to_html())
wnd.size= (600,600)
wnd.setVisible(1)
else:
self._print_table(result)
elif type=='viewSource' or type=='procSource':
self.println(result)
elif type=='tableDesc':
self._print_table(result)
elif type=='error':
self.println(result)
# except (SQLException, PSQLException, SybSQLException), e:
except java.sql.SQLException, e:
self.println(e.getMessage())
# except:
# pass

Jan
Jul 18 '05 #3
[Jan Gregor]
I tried it again with SQLException only but my main loop ends with
uncatched com.sybase.jdbc2.jdbc.SybSQLException.


Strange indeed. The only explanation I can think of offhand for the
exception not being caught is if com.sybase.jdbc2.jdbc.SybSQLException
is not a subclass of java.sql.SQLException.

Unfortunately, I can't seem to find the javadoc for the Sybase JDBC
driver online (which is poor performance from Sybase).

Try code of the following form to see what the nature of the exception is

import java.lang.Exception
import java.sql.SQLException

try:
# Insert your exception generating code here
except java.lang.Exception, jlx: # Catch every possible java exception
if isinstance(jlx, java.sql.SQLException):
print "Exc %s is subclass of java.sql.SQLException" % jlx.toString()
else:
print "Exc %s != subclass of java.sql.SQLException!" % jlx.toString()

Run that and let us know what the output is.

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
Jul 18 '05 #4
There's result - i put aa on input to force error:

Exc com.sybase.jdbc2.jdbc.SybSQLException: Stored procedure 'aa' not
found. Specify owner.objectname or use sp_help to check whether the
object exists (sp_help may produce lots of output).
!= subclass of java.sql.SQLException!
Problem is that SybSQLException IS subclass of SQLException - verified
by Eclipse IDE (type hierarchy). Similar effects were with jdbc driver
for PostgreSQL.

There's result:
Exc org.postgresql.util.PSQLException: ERROR: syntax error at or near
"aa"
!= subclass of java.sql.SQLException!
Jan

Jul 18 '05 #5
[Jan Gregor]
There's result - i put aa on input to force error:
What execution environment are you running it in when you have this
problem? A servlet container? Eclipse? From the command line?

I'm beginning to suspect some form of classloader/classpath issue.
Exc com.sybase.jdbc2.jdbc.SybSQLException: Stored procedure 'aa' not
found. Specify owner.objectname or use sp_help to check whether the
object exists (sp_help may produce lots of output).
!= subclass of java.sql.SQLException!
So your jython code finds that the exception raised does not subclass
the base exception it is trying to catch. Which could mean that the
definitions of the base exception class may be different between the
code trying to catch the exception (your jython) and the code trying to
raise it (Sybase jdbc).

Try the following experiments to see if you get behaviour that is different

1. Try this jython

import java.sql

try:
raise java.sql.SQLWarning() # known subclass of SQLException
except java.sql.SQLException:
print "Successfully caught"
else:
print "Big trouble in Little China"

2. Write some similar code to the above in java, raising an SQLWarning
when an object is created, e.g.

TestSubclassExceptions.java <---------->
import java.sql;

public TestSubclassExceptions
{
public TestSubclassExceptions ( )
throws SQLWarning
{
throw new SQLWarning();
}
}
<-------------------------------------->

Making sure that the class definition is on your classpath, instantiate
a TestSubclassExceptions object inside a jython try..catch as in #1, and
see what happens.

3. Write a version of the above class that raises
com.sybase.jdbc2.jdbc.SybSQLException instead. Make sure to run this one
from the command line, so that you know that the jython classloader is
the one loading the class and exception definitions.

If you're running inside some form of "enterprise container", you may be
tripping over a classloader issue, where base classes/exceptions are
being loaded by different classloaders, possibly with different security
settings. Solving these problems is almost always a case of finding the
right library directory to put your jython.jar, etc, in. This can
sometimes require extensive documentation delving.

Final sanity check: are you setting the "python.home" property if/when
you are embedding jython? There are some minor complexities associated
with caching of "compiled" java packages. These can cause odd behaviour
if you are executing your code from two different execution
environments, e.g. debugging on a command line, and then also running in
a servlet container.

If none of the above sheds any light, please post back with the details
of the software you're using, and the locations in which you've placed
your jython.jar, your sybase jdbc jars, etc.
Problem is that SybSQLException IS subclass of SQLException - verified
by Eclipse IDE (type hierarchy). Similar effects were with jdbc driver
for PostgreSQL.

There's result:
Exc org.postgresql.util.PSQLException: ERROR: syntax error at or near
"aa"
!= subclass of java.sql.SQLException!


So it's definitely not a Sybase specific problem.

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
Jul 18 '05 #6
All tests passed ok, but problem is still there. I didn't mentioned that
mysql works fine.

My system is debian, something between woody and testing version. At
home I have similiar debian upgraded moved so far from potato to woody
to sarge - same behaviour.

Application runs from command line by 'jython TextConsole.py'. Jython is
version 2.1, running on java 1.4.2_05 (at home 1.4.1). PostgreSQL
(7.4.3) and jdbc driver (as jython) from debian testing distribution.
Jan
Jul 18 '05 #7
[Jan Gregor]
All tests passed ok, but problem is still there. I didn't mentioned that
mysql works fine.

My system is debian, something between woody and testing version. At
home I have similiar debian upgraded moved so far from potato to woody
to sarge - same behaviour.

Application runs from command line by 'jython TextConsole.py'. Jython is
version 2.1, running on java 1.4.2_05 (at home 1.4.1). PostgreSQL
(7.4.3) and jdbc driver (as jython) from debian testing distribution.


I have one more thing to suggest, and that only applies if you are
"embedding", i.e. calling jython created classes from java, as opposed
to calling java classes from jython.

If you are embedding, then you are initializing the jython runtime
yourself, as opposed to having jython do that for you. In these cases,
names of java packages are not always picked up from the jython package
cache (although the class definitions are picked up if the jar is
present on the classpath).

Try adding a line like this to the top of your jython module

import sys ; sys.add_package('com.sybase.jdbc2.jdbc')

This can also be done outside jython, in the java embedding environment,
through a PySystemState object, as described here

http://sourceforge.net/mailarchive/f...&forum_id=5586

If that doesn't help, I'm afraid I'll be too busy for the next few days
to help out, though there are other people here who might be able to
contribute.

The day I've been waiting for for 7 years has finally arrived: proof
that the US retail milk supply is contaminated with a bacterium known as
Mycobacterium avium subspecies paratuberculosis. I expect to be very
busy with this, especially if the US media reacts to the story the same
way that the British and Irish media did. If you see an article on
paratuberculosis and Crohn's Disease in the media in the next few days,
you'll be happy to know that python is an essential part of the
management of two of the main related web sites: www.crohns.org and
www.paratuberculosis.org

More info on paratuberculosis in US retail food from

http://www.johnes.org/newsfiles/109216471862392.html

my-world-is-tumbling-ly y'rs

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Dave Benjamin | last post by:
Hey good people, I've been doing a lot of simultaneous Jython and CPython programming lately, and just wanted to say, with no intended ill will...
0
by: Ike | last post by:
I have a signed JApplet which has a JTextArea wherein one can put Jython Script. Upon clicking a JButton, the script is executed. The script which...
4
by: angel | last post by:
A java runtime environment includes jvm and java class (for example classes.zip in sun jre). Of course jython need jvm,but does it need java class....
5
by: Maurice Ling | last post by:
Hi, I have read that this had been asked before but there's no satisfactory replies then. I have a module (pA) written in python, which...
3
by: Jim Hargrave | last post by:
I've read that it is possible to compile jython to native code using GCJ. PyLucene uses this approach, they then use SWIG to create a Python...
12
by: Mark Fink | last post by:
I wrote a Jython class that inherits from a Java class and (thats the plan) overrides one method. Everything should stay the same. If I run this...
3
by: donkeyboy | last post by:
All, I'm having issues installing Jython on Windows XP. I've looked on the web and this newsgroup but to no avail. Any suggestions? The shell...
2
by: donkeyboy | last post by:
All, I've tried the jythonc compiler to try and create an applet to see how it works, but I get a number of Java compile errors that are way...
5
by: sarup26 | last post by:
Hello .. I would like to know more about Python and Jython? What is the difference between both of them? What is the future for Jython and which...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
0
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand....
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.